为什么我的变量的更改在此函数之外不可见?

Why aren't the changes to my variable being visible outside of this function?

下面的代码是一个 D3 片段,放在 VueJS 实例中。该代码段会创建圆圈并让您拖动它们。

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。但是第二个 long,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];

希望对您有所帮助。