如何在VueJS中使数组具有反应性

时间:2020-07-05 02:50:14

标签: vue.js vuejs2

我正在尝试使用Vue在图像上添加一个简单的悬停效果,以便悬停显示的图像数组中的第二项。如果数据已更改,我无法找到不断更新模板数据的最佳方法。我尝试了计算机,对我也没有用。

在console.log()中,所有方法的更新都很好。但不适用于观察者或计算得出的人。

我看到手表只能在Mount上工作,而不能在mouseenter上工作。

         <div class="cursor-pointer" v-for="(image, index) in images" :key="index"
                  @mouseenter="hoverEnter(index)"
                  @mouseleave="hoverLeave(index)"
                  >
// MOUSE OVER IS NOT UPDATING
                    <div><img :src="mouseOver[index] ? image[1].src : image[0].src"></div>
         </div>
         data() {
            return {
              id: this.$route.params.id,
              images: [],
              mouseOver: []
            };
         },
         mounted() {
          this.returnImages
            this.mouseOver = this.currentCollection.products.map((res) => {
            return false
          })
        },
         methods: {
                hoverEnter(index) {
                  this.mouseOver[index] = true
                },
                hoverLeave(index) {
                  this.mouseOver[index] = false
                },
          },
          watch: {
                mouseOver: function (newValue) {
                  console.log(newValue) // THIS IS NOT UPDATING
                }
          },

1 个答案:

答案 0 :(得分:0)

我能够使用Vue的this。$ set使它具有反应性,并卸下手表。编辑:知道了,它的拼接形式很好。我使数据无反应。希望这对某人有帮助。

通过直接设置索引(例如arr [0] = val)或修改其length属性来修改Array时。同样,Vue.js无法获取这些更改。始终通过使用Array实例方法或完全替换它来修改数组。

他们说。https://vuejs.org/2016/02/06/common-gotchas/

arr.splice(索引,1,值)

Vue Set

   methods: {
    hoverEnter(index) {
      this.$set(this.mouseOver, index, true)
      console.log(this.mouseOver)
    },
    hoverLeave(index) {
      this.$set(this.mouseOver, index, false)
      console.log(this.mouseOver)
    },
  },

拼接

methods: {
    hoverEnter(index) {
      this.mouseOver.splice(index, 1, true)
      console.log(this.mouseOver)
    },
    hoverLeave(index) {
      this.mouseOver.splice(index, 1, false)
      console.log(this.mouseOver)
    },
  },