Consider a Todo list with filtering functionality:
list.vue:
<script>
import TodoItem from './todo_item.vue';
export default {
components: { TodoItem },
props: ['selectedPriority'],
data: {
items: [
{ name: 'Do shopping', priority: 'high' },
{ name: 'Play games', priority: 'low' }
]
},
computed: {
selectedItems: function() {
if(this.selectedPriority == 'all') {
return this.items;
} else {
var selectedPriority = this.selectedPriority;
return this.items.filter(function(item) {
return item.priority == selectedPriority
});
}
}
},
}
</script>
<template>
<div>
<select v-model="selectedPriority">
<option value="all">All</option>
<option value="low">Low</option>
<option value="high">High</option>
</select>
<todo-item
v-for="item in selectedItems"
:name="item.name"
:priority="item.priority"
/>
</div>
</template>
todo_item.vue:
<script>
export default {
props: ['name', 'priority']
}
</script>
<template>
<div>
<p>{{ name }}</p>
<select v-model="priority">
<option value="low">Low</option>
<option value="high">High</option>
</select>
</div>
</template>
html:
<list />
If, for instance, the filter is set to all
, and I change the priority of Play games
to high
and switch the filter to high
, only Do shopping
will be displayed. This is because the priority was not updated in the items
collection and it triggered a re-render.
What is the correct method to update collection data from child components in Vue.js?