The Vue pattern is props
down and events
up. It sounds simple, but is easy to forget when writing a custom component.
As of Vue 2.2.0 you can use v-model (with computed properties). I have found this combination creates a simple, clean, and consistent interface between components:
- Any
props
passed to your component remains reactive (i.e., it's not cloned nor does it require a watch
function to update a local copy when changes are detected).
- Changes are automatically emitted to the parent.
- Can be used with multiple levels of components.
A computed property permits the setter and getter to be separately defined. This allows the Task
component to be rewritten as follows:
Vue.component('Task', {
template: '#task-template',
props: ['list'],
model: {
prop: 'list',
event: 'listchange'
},
computed: {
listLocal: {
get: function() {
return this.list
},
set: function(value) {
this.$emit('listchange', value)
}
}
}
})
The model property defines which prop
is associated with v-model
, and which event will be emitted on changes. You can then call this component from the parent as follows:
<Task v-model="parentList"></Task>
The listLocal
computed property provides a simple getter and setter interface within the component (think of it like being a private variable). Within #task-template
you can render listLocal
and it will remain reactive (i.e., if parentList
changes it will update the Task
component). You can also mutate listLocal
by calling the setter (e.g., this.listLocal = newList
) and it will emit the change to the parent.
What's great about this pattern is that you can pass listLocal
to a child component of Task
(using v-model
), and changes from the child component will propagate to the top level component.
For example, say we have a separate EditTask
component for doing some type of modification to the task data. By using the same v-model
and computed properties pattern we can pass listLocal
to the component (using v-model
):
<script type="text/x-template" id="task-template">
<div>
<EditTask v-model="listLocal"></EditTask>
</div>
</script>
If EditTask
emits a change it will appropriately call set()
on listLocal
and thereby propagate the event to the top level. Similarly, the EditTask
component could also call other child components (such as form elements) using v-model
.