0👍
As you already said: "showDetails method only runs at the beginning of the page loading". Vue doesn’t know when to call the showDetails
method again. A method must be called and executed explicitly in order to run.
In your case, you can use a computed property to achieve what you are trying to do.
0👍
Call it in computed instead of method
<template>
<div v-for="(person, index) in people" :key="index">
<div @click="detailsOpened(index)">
<PersonIcon v-if="personDetailsOpen(index)" />
<PersonIcon2 v-else />
</div>
</div>
</template>
<script>
export default {
data() {
return {
personMap: [],
people: [...] // initialize with your data
};
},
methods: {
detailsOpened(index) {
this.$set(this.personMap, index, !this.personMap[index]);
}
},
computed: {
personDetailsOpen() {
return (index) => this.personMap[index] === true;
}
}
};
</script>
0👍
Vue does not react when you directly update the item at its index. You need to use the set operator to make it reactive. Please look at this answer too for more understanding.
On another hand, here is a working demo of your use-case where I used a set to update the personMap
array’s item.
new Vue({
el: "#app",
data() {
return {
people: [1, 2, 3],
personMap: []
}
},
beforeMount() {
this.personMap = this.people.map(item => item = false);
},
methods: {
showDetails(index) {
return this.personMap[index] === true
},
detailsOpened(index) {
this.$set(this.personMap, index, !this.personMap[index])
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-for="(person, index) in people" :key="index">
<div @click="detailsOpened(index)">
<div v-if="showDetails(index)">Clicked</div>
<div v-else>Click me</div>
</div>
</div>
</div>
- [Vuejs]-How to use "iconClass" prop in a BalmUI "floating action button" component?
- [Vuejs]-How can i set the focus to vue flat-pickr component?
Source:stackexchange.com