Vue组件间通信(非VueX)

基于以下情况

//父组件
data:{
    //对象形式
}

//子组件
data:function(){
  return {
       //函数形式  
   }
}

例子如下

<div id="app">
   //父组件
    <p>{{total}}</p>
    <mime @increment1="incrementTotal" ref="child" :num-a="total" num-s="total"></mime>
    
    <button type="button" @click="clickref">调用子组件</button>
</div>

//子组件
<template id="myInput">
    <button @click="add">{{counter}}</button>
</template>
<script>
    new Vue({
        el:'#app',
        data :{
            total: 0          
        },
        methods:{
            incrementTotal : function(){
              
            },
            clickref:function(){
              
            }
        },
        components:{
            'mime' :{
                template:'#myInput',
                data : function(){
                    return{
                        counter : 0
                    }
                },
                props:['numA','numS'],
                methods:{
                    add : function(){
                      
                    }
                }
            }
        }
    });
</script>

子组件调用父组件

{{total}}
<mime @increment="incrementTotal"></mime>

<template id="myInput">
    <button @click="add">{{counter}}</button>
</template>

...
<script>
....
data:{
   tatal: 0
},
methods:{
   incrementTotal:function(){
       this.total +=1;
   }
},
components:{
   data : function(){
       return:{
          counter : 0
       }
   },
    methods : {
        add : function(){
             this.counter +=1;
             this.$emit('increment'); //子组件通过 $emit触发父组件的方法 increment   还可以传参   this.$emit('increment' ,this.counter);
        }
   }
}
</script>

父组件调用子组件

<mime ref="child"></mime>
<button type="button" @click="clickref">调用子组件</button>

<template id="myInput">
    <button @click="add">{{counter}}</button>
</template>

...
<script>
....

methods:{
   clickref:function(){
          var child = this.$refs.child; //获取子组件实例
          child.counter = 45;           //改变子组件数据
          child.add(11);                //调用子组件方法 add
       }
},
components:{
   data : function(){
       return:{
          counter : 0
       }
   },
    methods : {
        add : function(num){
             this.counter +=1;
             console.log('接受父组件的值:',num) //num为11
        }
   }
}
</script>

组件间互调


//新建一个空的
var bus = new Vue()
// 触发组件 A 中的事件
bus.$emit('id-selected', 1)
// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
// ...
})

总结: 太繁琐,直接用Vuex

 

转载于:https://my.oschina.net/u/1031097/blog/1526631

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值