Search code examples
vue.jsvue-componentv-for

trying to change image of a component in vue js but it's touching the entire row


so i'm trying to change the img src on hover events on a component. it works but since i use v-for, it change every image in the row instead of one. here is the code in main.js :

Vue.component("fiche-produit", {
            template: `<div class="col-3">
                            <img v-bind:src="image" width="380px">             
                        </div>`,
            props: ["image"],
            methods: {},
        });
        new Vue({
            el: "#app",
            data: function () {
                return {
                    hover: false,
                    produits: [{
                            id: "1",
                            nom: "",
                            image: "img/coupe-vent-home-menthe.jpg",
                            image2: "img/technique_mente2.jpg",
                            prix: "",
                        },
                        {
                            id: "2",
                            nom: "",
                            image: "img/Bas_de_jogging_technique_menthe1.jpg",
                            image2: "img/Bas_de_jogging_technique_menthe2.jpg",

                            prix: "",
                        },
                        {
                            id: "3",
                            nom: "",
                            image: "img/coupe-vent-home-noir.jpg",
                            image2: "img/coupe-vent-home-noir2.jpg",
                            prix: "",
                        },
                        {
                            id: "4",
                            nom: "",
                            image: "img/bas_technique_noir.jpg",
                            image2: "img/bas_technique_noir2.jpg",
                            prix: "",
                        }
                    ],
                };
            },
        });

here is the html code:

<div id="app">
        <fiche-produit v-for="produit in produits" @mouseover.native="hover = true" @mouseleave.native="hover = false"
            v-bind:image="[hover ? produit.image2 : produit.image]"></fiche-produit>
    </div>

Solution

  • You have multiple produits but only a single hover state variable, which is shared by all of them. If you want each to have their own hover state, you will need separate variables. You can either have a hover array of the same length as produits, or just add a hover attribute to each.

    For example:

    <fiche-produit v-for="produit in produits"
                   @mouseover.native="$set(produit, 'hover', true)" 
                   @mouseleave.native="$set(produit, 'hover', false)"
                   v-bind:image="[produit.hover ? produit.image2 : produit.image]"
                   :key="produit.id">
    </fiche-produit>