Vue.js父与子组件之间传参示例

2020-06-16 06:00:33易采站长站整理

childWords: ""
}
},
components: {
componentA
},
methods: {
listenToMyBoy: function (msg){
this.childWords = msg
}
}
})
}

componentA.vue中


<button v-on:click="onClickMe">like!</button>


import componentA from './components/componentA'
export default {
data: function () {
return {
msg: 'I like you!'
}
},
methods: {
onClickMe: function(){
this.$emit('child-say',this.msg);
}
}
}

子组件向父传参(.$dispatch)

用法:vm.$dispatch( event, […args] ),派发事件,首先在实例上触发它,然后沿着父链向上冒泡在触发一个监听器后停止。

例子:App.vue中events中注册”child-say”事件。子组件componentA中,单击按钮后触发”child-say”事件,并传参msg给父组件。父组件中”child-say”方法把msg赋值给childWords,显示在<p>标签中。

App.vue中


<p>Do you like me? {{childWords}}</p>
<component-a msgfromfa="(Just Say U Love Me)"></component-a>


import componentA from './components/componentA'
export default {
new Vue({
events: {
'child-say' : function(msg){
this.childWords = msg
}
}
})
}

componentA.vue中


<button v-on:click="onClickMe">like!</button>


import componentA from './components/componentA'
export default {
data: function () {
return {
msg: 'I like you!'
}
},
methods: {
onClickMe: function(){
this.$dispatch('child-say',this.msg);
}
}
}