vue 组件之间的通信(父子、非父子)

//子组件向父组件传递数据
<div id="app">
    <test-child receive-child="标题"></test-child>
</div>

 - 在子组件test-child使用 props 声明: props:['receiveChild']
  然后父组件就可以向trans里传递数据,动态数据需加冒号 :receive-child="fathermsg"

 - 为 prop 指定验证规则,如果传入的数据不符合要求,Vue 会发出警告。
   props:{
           'recStr':{
                type:String,    //类型不要加引号
                default:"我是默认字符串"
                }
           'recArr':{
                type:Array,    
                default:function(){    //数组和对象需用函数返回数据
                    return ["第1项","第2项""第3项"]
                    }
                }
           }
//子组件向父组件传递数据:
<div id="app">
    {{showMsg}}
    <test-child @send="getChild"></test-child>
</div>

 - 在子组件的HTML里定义一个触发事件:
   <li @click="sendMsg">点击我触发</li>
 - 在子组件的methods:
   sendMsg:function(ev){
        this.$emit('send',ev.target.innerHtml)  //send是自定义事件,后面的是参数
       }
 - 在父组件的methods里:
   getChild:function(str){
        this.showMsg=str    //showMsg在父组件的data里定义
    }
//非父子组件间的通信:
<div id="app">
    <test-header></test-header>
    <test-list></test-list>
</div>
 - 空实例方法:
   $emit   //发布
   $on    //订阅 
///////////////////////////////////////
//list向header传递数据:
 - 定义一个空实例:
   var busVm = new Vue();

 - 在list组件里定义一个触发事件:
   <li @click="sendMsg">点击我触发</li>

 - 在list组件的methods发布:
   sendMsg:function(ev){
        busVm.$emit('send',123)  //send是自定义事件,后面的是参数

 - 在header组件的mounted里订阅:
   mounthe:function(){
        busVm.$on('send',function(num){
           console.log(num);
        }.bind(this))
    }

猜你喜欢

转载自blog.csdn.net/qq_33325959/article/details/79015634