1

I am trying to add a simple hover effect on images with Vue, so that on hover the second item in the array of images in shown. I cannot work out the best way to constantly update the templates data if the data has changed. I tried Computed, didn't work either for me.

Everything updates fine in console.log() for the methods. But not for watchers or computed.

I see that watch works only on Mount, but not on 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 Answer 1

1

I was able to make this reactive using the this.$set from Vue and remove the watch. Edit: Got it, it's splice in nice form. I made my data non reactive. Hope this helps someone.

When you modify an Array by directly setting an index (e.g. arr[0] = val) or modifying its length property. Similarly, Vue.js cannot pickup these changes. Always modify arrays by using an Array instance method, or replacing it entirely.

they say.https://vuejs.org/2016/02/06/common-gotchas/

arr.splice(index, 1, value)

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

Splice

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)
    },
  },
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.