簡體   English   中英

Vue函數未更新數據變量

[英]Vue function not updating data variable

我已經設置了使用Vue和Greensock可拖動的頁面,以嘗試使矩形svg對象在屏幕上可拖動。 我想知道何時拖動對象,所以我設置了一個數據變量hasDragged:false。

我在dragstart上使用addEventListener設置了一個函數,當它檢測到已拖動該變量時會將其更新為true,但是它僅更新函數中的變量,而不更新我需要的數據變量。 該功能在更新的生命周期掛鈎中的另一個功能內,因此我想知道是否無法從第二個功能內更新this.hasDragged是一個問題。

我嘗試了可拖動的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

向下滾動到標題為Config object properties的部分

現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM