亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 312 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號