vue函数不更新数据变量



我已经使用vue和greensock拖动设置了一个页面,以尝试在屏幕上拖动矩形SVG对象。我想知道何时拖动对象,因此我设置了一个数据变量jusdraged:false。

在DragStart上使用AddEventListener,我设置了一个函数,该函数将在检测到已被拖动时将其更新为true,但是它仅在功能中更新了变量,而不是我需要的数据变量。该功能在更新的生命周期挂钩中的另一个函数中,因此我想知道这是否是无法更新此功能的问题。

我尝试了许多版本的可拖动AddeventListener,试图通过函数将其传递,将变量分配给每个函数,将变量分配为常数和其他一些内容。

new Vue({
      el: "#app",
      data: {
        hasDragged: false
      },
updated: function(hasDragged) {
        var petDrag = Draggable.create(".icon",{
                bounds:"#container"
              })[0];
              petDrag.addEventListener("dragstart", dragStart);     
              function dragStart () {            
              this.hasDragged = true; 
        }
The expected result is that the hasDragged variable at the Vue data level will be updated to true when the svg object is dragged. The actual result is that only the variable within the second function is updated to true but the Vue data variable remains false.

this内部功能不是vue实例。您可以为此使用箭头功能:

new Vue({
  el: "#app",
  data: {
    hasDragged: false
  },
  updated: function () {
    var petDrag = Draggable.create(".icon", {
      bounds: "#container"
    })[0];
    petDrag.addEventListener("dragstart", () => {
      this.hasDragged = true
    });
  }
})

我在这里参加聚会有点晚,但我只是想补充ittus的回答。

所有GSAP构造函数都具有非常完整的事件回调集,并且在任何一个都可以指定该特定回调内的范围,这意味着您可以在不直接添加匿名函数的情况下设置this的位置(不是那样(它有任何问题(。因此,在这种情况下,可以在Draggable构造函数中添加代码(我正在使用$refs来获取代码中的实际DOM元素(:

data: function () {
  return {
    blueDragged: false
  };
},
methods: {
  blueDragStarted: function () {
    this.blueDragged = true;
  },
},
mounted: function () {
  Draggable.create(this.$refs.blueElement, {
    type: "x, y",
    onDragStart: this.blueDragStarted,
    onDragStartScope: this // Vue component instance
  });
},

在此示例中,我们利用正在创建Draggable实例的上下文。在此上下文中,this是指组件实例,我们将其作为参考,确保我们可以在回调中访问组件的状态。

再次,Ittus的回答实际上没有错,只是感觉就像GSAP在这方面所提供的所有可能性补充。

您可以在此处看到GSAP Draggable的文档:

https://greensock.com/docs/utilities/draggable

向下滚动到标题为配置对象属性

的部分

实时演示

最新更新