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))
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值