Composing Components
Vue.js 2.x系で親子コンポーネント間のデータの受け渡し方法
by bc_rikko
HTML
<script src="https://unpkg.com/vue@2.0.3/dist/vue.js"></script>
<div id="app">
<div class="parent">
<h2>Parent</h2>
<p>{{ messageFromChild }}</p>
<p>{{ messageVModel }}</p>
</div>
<my-child parent-message="literal-from-parent" v-on:apply-from-child="apply" v-model="messageVModel"></my-child>
</div>
JavaScript
Vue.component('my-child', {
template: [
'<div class="child">',
'<h2>Child Component</h2>',
'<input type="text" v-model="childMessage" v-on:input="onInput"></input>',
'<button @click="apply">apply</button>',
'<p>{{ parentMessage }}</p>',
'<p>{{ value }}</p>',
'</div>'
].join(''),
props: ['parentMessage', 'value'],
data () {
return {
childMessage: ''
}
},
methods: {
apply () {
this.$emit('apply-from-child', this.childMessage)
},
onInput (e) {
this.$emit('input', e.target.value)
}
}
})
const app = new Vue({
el: '#app',
data () {
return {
messageFromChild: 'message from child',
messageVModel: 'message v-model'
}
},
methods: {
apply (value) {
this.messageFromChild = value
}
}
})