JSFiddle - React, Tailwind, and code Playground
by gongzza
HTML
<div id="app"></div>
<template id="parent">
<div>
Parent: <button @click="init()">Init</button><br>
<div v-for="item of items">
<input type="text" v-model="item.label">
{{item.label}}
</div>
Children: <br>
<child v-for="item of items" v-model="item.label"></child>
</div>
</template>
<template id="child">
<div>
<input type="text" v-model="text" @keyup.enter="updateValue">
{{text}}
</div>
</template>
JavaScript
Vue.component('child', {
template: '#child',
props: {
value: String
},
data() {
return {
text: ''
}
},
beforeMount() {
this.init()
this.$parent.$on('init', this.init)
},
beforeDestory() {
this.$parent.$off('init', this.init)
},
methods: {
init() {
this.text = this.$props.value
},
updateValue() {
this.$emit('input', this.text)
}
}
})
Vue.component('parent', {
template: '#parent',
data() {
return {
items: [
{label: 'a'},
{label: 'b'},
{label: 'c'}
]
}
},
methods: {
init() {
this.$emit('init')
}
}
})
new Vue({
el: '#app',
template: `<parent></parent>`
})