4👍
The short answer is that you should keep your state entirely in the parent component. Simply emit an event when the checkbox is changed and inform the parent when to alter its state.
You could implement the ws component like this:
export default {
props: {
active: {
type: Boolean,
required: true,
},
},
methods: {
onChange() {
this.$emit('toggle');
},
},
};
Note:
- We have removed
data
- You’ll need to call
onChange
from your template. Replace@change="active = !active"
with@change="onChange"
.
The parent component should declare an an array of ws data like so:
data() {
return {
wsData: [
{ name: 'Boston', active: false },
{ name: 'Seattle', active: false },
{ name: 'San Francisco', active: true },
{ name: 'New York', active: false },
],
};
},
The parent template could render the set of ws components like this:
<ul>
<li v-for="(ws, index) in wsData" :key="index">
<WS :agency="ws.name" :active="ws.active" @toggle="toggleState(index)" />
</li>
</ul>
Finally you’ll add a toggleState
method like this:
methods: {
toggleState(index) {
this.wsData[index].active = !this.wsData[index].active;
}
}
As an aside, I suggest using eslint-plugin-vue, and crank it up to plugin:vue/recommended
. This will prevent you from doing things like declaring a data
key that shadows one of your props.
- [Vuejs]-Tabulator – how to display a loading indicator while data is fetched from db based on a prop?
- [Vuejs]-Property or method "_" is not defined on the instance but referenced during render
Source:stackexchange.com