Reputation:
I'd like to change the src from the specific image clicked only, but it's changing all images. All the solutions I could find show elements in loop, which is not the case here:
<div id="app">
<div>
<img :src="icon" @click="change" />
</div>
<div>
<img :src="icon" @click="change" />
</div>
<div>
<img :src="icon" @click="change" />
</div>
</div>
const app = Vue.createApp({
data() {
return {
icon: 'index.png'
}
},
methods: {
change() {
this.icon = 'icon.png'
}
}
})
app.mount('#app')
Upvotes: 0
Views: 135
Reputation: 356
The reason they all update at once is that they all get their src
value from the same property. If you're wanting to change them individually, they'll all need their own properties and modifications to the change
method so it knows what to update.
Try doing something like this:
<template>
<img :src="icon1" @click="change('icon1')" />
<img :src="icon2" @click="change('icon2')" />
<img :src="icon3" @click="change('icon3')" />
</template>
<script>
export default {
name: "App",
data() {
return {
icon1: "index.png",
icon2: "index.png",
icon3: "index.png",
};
},
methods: {
change(prop) {
this[prop] = "icon.png";
},
},
};
</script>
I created a simple codesandbox that should show it in action.
Upvotes: 2