【问题标题】:How to make Arrays reactive in VueJS如何在 VueJS 中使数组具有响应性
【发布时间】:2020-07-05 02:50:14
【问题描述】:

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

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
                }
          },

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

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

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

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

    arr.splice(index, 1, value)

    Vue 集

       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)
        },
      },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-27
      • 2020-08-25
      • 2018-08-01
      • 2018-07-20
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      相关资源
      最近更新 更多