<app>
我是跟组件
<child></child>
</app>
<div>
<p>我是子组件</p>
<p>{{message}}</p>
<button></button>
</div>
- 子向父传参
在子组件中
<button @click="submit()"></button>
submit () {
this.$emit('childFn',this.message)
}
在父组件中
<app>
<child @childFn="parentFn"></child>
</app>
//在methods中,写一个 parentFn() 函数,写入传的参数,获取子组件中 message 的值:
parentFn (message) {
this.getMessage = message
}
2 父组件向子组件传值
在子组件中
export default {
props: ['childMessage'],
data () {
return {
...
}
}
在父组件中
<app>
<child :childMessage="parentMessage"></child>
</app>
export default {
data () {
return {
parentMessage: '我是要传递的值'
}
}
全局事件总线
main.js:
//创建vm
new Vue({
el:'#app',
render: h => h(App),
// beforeCreate中模板未解析,且this是vm
beforeCreate(){
Vue.prototype.$bus = this //安装全局事件总线
}
})
接下来,我们就要对想要接收到数据的组件进行自定义事件的绑定,简单来说就是,谁要接收数据,自定义事件就绑定在谁身上
A向B传值
TestB.vue:
mounted(){
// 绑定自定义事件
this.$bus.$on('自定义事件名', (接收参数)=>{
console.log('我是TestB组件,收到了数据', 接收参数);
})
}
TestA.vue:
methods:{
// 触发事件,事件名不能重复
触发事件方法名(){
this.$bus.$emit('自定义事件名', 传递参数);
}
},
5241

被折叠的 条评论
为什么被折叠?



