[英]Why aren't the changes to my variable being visible outside of this function?
以下代碼是在VueJS實例中插入的D3。 該代碼段創建了圓圈,並允許您拖動它們。
new Vue({
el: 'body',
data: {
x: '',
y: ''
},
computed: {
pos: function () {
function click() {
var point = d3.mouse(this),
p = { x: point[0], y: point[1] }
svg.append('circle')
.attr('transform', 'translate(' + p.x + ',' + p.y + ')')
.attr('r', '5')
.attr('class', 'dot')
.style('cursor', 'pointer')
.call(drag)
var dots = d3.selectAll(".dot")
var svg = d3.select('body').append('svg')
.attr('width', 400)
.attr('height', 400)
.on('click', click)
var drag = d3.behavior.drag()
.on('drag', dragmove)
function dragmove(d) {
var x = d3.event.x
var y = d3.event.y
d3.select(this).attr('transform', 'translate(' + x + ',' + y + ')')
this.x = x
console.log('x:', this.x)
}
console.log('x:', this.x)
}
},
ready: function () {
}
})
現在,我試圖獲取拖動圓的位置x。 第一個console.log('x:', this.x)
記錄位置: x: 190
。 但是第二個很長的時間, dragmove()
函數之外的那個並沒有記錄任何內容。
如何使第二個console.log
記錄this.x
的值?
這是JSFiddle: https ://jsfiddle.net/alexcheninfo/unejge3k/1
如果要在dragmove
函數外部訪問x
,則必須在外部范圍內定義x
。
var x, y;
function dragmove(d) {
x = d3.event.x
y = d3.event.y
d3.select(this).attr('transform', 'translate(' + x + ',' + y + ')')
this.x = x
console.log('x:', this.x)
}
console.log('x:', this.x)
但是我真的不推薦這種方法。
由於您需要平移圓,因此可以這樣做。
var c = svg.append('circle')
.attr('transform', 'translate(' + p.x + ',' + p.y + ')')
.attr('r', '5')
.attr('class', 'dot')
.style('cursor', 'pointer')
.call(drag)
var trans = d3.transform(c.attr('transform')).transalte;
var tx = trans[0];
var ty = trans[1];
希望這會幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.