为了账号安全,请及时绑定邮箱和手机立即绑定

Vue函数不更新数据变量

Vue函数不更新数据变量

喵喔喔 2021-07-02 11:01:40
我已经使用 Vue 和 Greensock 可拖动设置了一个页面,以尝试在屏幕上制作一个可拖动的矩形 svg 对象。我想知道对象何时被拖动,所以我设置了一个数据变量 hasDragged: false。在 dragstart 上使用 addEventListener 我设置了一个函数,当它检测到它已被拖动时,它将将该变量更新为 true,但是它只更新函数内的变量,而不是我需要的数据变量。该函数在更新的生命周期钩子中的另一个函数中,所以我想知道这是否是无法从第二个函数中更新 this.hasDragged 的问题。我已经尝试了可拖动 addEventListener 的许多版本,尝试通过函数传递它,在每个函数中为 this 分配变量,将变量分配为常量和其他一些东西。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.
查看完整描述

2 回答

?
跃然一笑

TA贡献1826条经验 获得超6个赞

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

    });

  }

})


查看完整回答
反对 回复 2021-07-15
  • 2 回答
  • 0 关注
  • 373 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号