(1)父组件事先在子组件内部写入一个函数
1.首先在父组件<App>中绑定传给子组件的数据
<MyHeader @addTodo="addTodo"/>
2.在父组件methods中写出功能
addTodo(todoObj){this.todos.unshift(todoObj)},
3.在子组件中引入
props:["addTodo"]//通知app组件添加对象this.addTodo(todoObj)
(2)$emit
1.首先在子组件定义一个方法,当方法执行的时候调用this.$emit('自定义的方法名','要给父组件的值')
的方法来提交值
checkAll(e){this.$emit("checkAllTodo",e)}
2.在通过父组件中的子组件通过v-on或者@来绑定刚才的方法,当这个方法执行的时候后面会触发另外一个方法,在这个方法中的第一个参数就是传过来的值,然后可以处理这个值
@checkAllTodo="checkAllTodo" checkAllTodo(done){this.todos.forEach((todo)=>{todo.done=done})}
(3)事件总线
1.安装全局事件总线
//创建vue实例对象vmnew Vue({el:'#app',//完成了将app组件放入容器中的功能render: h => h(App),beforeCreate(){Vue.prototype.$bus = this //安装全局事件总线}})
2.组件A写入触发事件
sendStudentName(){this.$bus.$emit("hello",this.name)}}
3.组件B执行并销毁
mounted(){this.$bus.$on("hello",(data)=>{console.log(data)})},beforeDestroy(){this.$bus.$off("hello")}
(4)消息订阅
1.发送消息组件
sendStudentName(){pubsub.publish("hello",666)}
2.订阅消息组件
mounted(){this.pubId=pubsub.subscribe("hello",function(msgName,data){console.log("发布hello",msgName,data)})},beforeDestroy(){pubsub.unsubscribe("this.pubId")}
(5)ref的应用
// component-a 子组件export default{data () { return{title: 'Vue.js'}},methods: {sayHello () {window.alert('Hello');}}}// 父组件<template><component-a ref="comA"></component-a></template><script> export default{mounted () { const comA = this.$A;console.log(comA.title); // Vue.jscomA.sayHello(); // 弹窗}}</script>