[英]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.