Use v-model
to update the state:
Vue.component('shortcuts', {
props: {
value: Array // Of shortcuts
},
methods: {
add: function () {
const newValue = [...this.value, { action: '' }]
this.$emit('input', newValue)
},
remove: function (index) {
const newValue = [...this.value]
newValue.splice(index, 1)
this.$emit('input', newValue)
}
},
template: '<div>
<shortcut-entry v-for="(shortcut, index) in value" is="shortcut-entry" v-bind:key="index" v-bind="shortcut" @remove="remove(index)"></shortcut-entry>
<br>
<button v-on:click=add>Add</button>
</div>'
And the parent component is something like this:
Vue.component('parent-comp', {
data () {
return {
shortcuts: []
}
},
template: '<shortcut v-model="shortcuts"></shortcut>'
})
*** Use .sync ***
Vue.component('shortcuts', {
props: {
shortcuts: Array // Of shortcuts
},
methods: {
add: function () {
const newValue = [...this.shortcuts, { action: '' }]
this.$emit('update:shortcuts', newValue)
},
remove: function (index) {
const newValue = [...this.shortcuts]
newValue.splice(index, 1)
this.$emit('update:shortcuts', newValue)
}
},
template: '<div>
<shortcut-entry v-for="(shortcut, index) in shortcuts" is="shortcut-entry" v-bind:key="index" v-bind="shortcut" @remove="remove(index)"></shortcut-entry>
<br>
<button v-on:click=add>Add</button>
</div>'
})
So, the caller component:
Vue.component('parent-comp', {
data () {
return {
shortcuts: []
}
},
template: '<shortcut :shortcuts.sync="shortcuts"></shortcut>'
})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…