Vue2.0组件通信(非Vuex)



最近学了Vue2.0,写写自己的一点总结,关于父子组件通信的,这点对于我来说,是看文档的时候比较难理解的。通过网上找资料和实践,也有一点理解。

例子使用以下代码模板

<script src="https://cdn.bootcss.com/vue/2.1.10/vue.min.js"></script>
<div id="app">
    <!--父组件-->
    <p>{{total}}</p>
    <child @add="incrementTotal" ref="childTest" :num-a="total" num-s="total"></child>
    <button type="button" @click="clickref">调用子组件</button>
</div>

<!--子组件-->
<template id="myChild">
    <button @click="add">{{counter}}</button>
</template>

<script>
    new Vue({
        el:'#app',
        data :{
            total: 1          
        },
        methods:{
            incrementTotal : function(){

            },
            clickref:function(){

            }
        },
        components:{
            'child' :{
                template:'#myChild',
                data : function(){
                    return{
                        counter : 0
                    }
                },
                props:['numA','numS'],
                methods:{
                    add : function(){

                    }
                }
            }
        }
    });
</script>

父组件传数据给子组件

当子组件需要父组件传递的数据时,子组件要设置props,来接收父组件传递过去的值。
在这里父组件传递的是total,子组件设置props[numA,numS],接着在调用子组件的时候将父组件的数据传递过去,如下

    <child :num-a="total" num-s="total"></child>

这样就可以子组件'child'就能接收到父组件(也就是挂载在 app上的)的数据。

关于props的写法有多种,具体请看官方文档

父子通信-动态数据

有时候我们想实现父组件的数据能动态的传递给子组件,使用v-model来实现

<input v-model="total">
<child :num-a="total">

<!--props的另外一种写法-->
<scirpt>
...
props: {
    numA: [String, Number]
}
</script>

子组件与父组件通信

有时候我们想要实现子组件调用父组件,那要怎么做呢?
我们可以通过触发事件来通知父组件改变数据。

父组件:

<div>
    <child @add="incrementTotal" :num-a="total"></child> //监听子组件触发的add事件,然后调用incrementTotal方法
</div>
methods: {
    incrementTotal() {
        this.total +=1
    }
}

子组件:

components:{
    'child' :{
        template:'#myChild',
        data : function(){
            return{
                counter : 0
            }
        },
        props:['numA','numS'],
        methods:{
            add : function(){
                this.counter +=1
                this.$emit('add') //子组件通过 $emit触发父组件的方法add
            }
        }
    }
}

子组件执行add方法 => 触发$emit => 触发父组件add方法 => 执行 incrementTotal 方法 => 完成

父组件调用子组件

通过给子组件设置ref,可以很方便的获取到子组件,然后改变子组件。

    <child @add="incrementTotal" ref="childTest" :num-a="total" num-s="total"></child>
new Vue({
    el:'#app',
    data :{
        total: 0          
    },
    methods:{
        incrementTotal : function(){
            this.total += 1
        },
        clickref:function(){
            let childRef = this.$refs.childTest //获取子组件
                childRef.counter = 1221         //改变子组件的数据
                childRef.add(11)                //调用子组件的方法
        }
    },
    components:{
        'child' :{
            template:'#myChild',
            data : function(){
                return{
                    counter : 0
                }
            },
            props:['numA','numS'],
            methods:{
                add : function(num){
                    this.counter +=1
                    this.$emit('add')
                    console.log('接收父组件的值':+ num)
                }
            }
        }
    }
});

子组件与子组件通信

如果2个组件不是父子组件那么如何通信呢?
这时可以通过eventHub来实现通信,
所谓eventHub就是创建一个事件中心,相当于中转站,可以用它来传递事件和接收事件。(或者使用vuex)

let eventHub = new Vue(); //创建事件中心

组件1触发:

<div @click="eve"></div>
methods: {
    eve() {
        eventHub.$emit('change','hehe'); //eventHub触发事件
    }
}

组件2接收:

<div></div>
created() {
    eventHub.$on('change', () => { //eventHub接收事件
        this.msg = 'hehe';
    });
}

这样就实现了非父子组件之间的通信了,原理就是把Hub当作一个中转站!

总结

例子代码:JSFiddle
参考:vue2.0父子组件以及非父子组件如何通信



写在前面:

1.父组件的data写法与子组件的data写法不同

复制代码
//父组件
data:{
    //对象形式
}

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

2.引用子组件遵循 

  • 引入组件
  • components里定义使用
  • 如果有通信,需要在子组件的props注册

以下实例全部使用以下模板

复制代码
<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>
复制代码

 

1.父子通信 之 静态数据

如果只是传单一的字符串 

<mime num-s="total"></mime>

....

props:['numS'] // numS  为字符串 total

这样子组件的numS一直为total。但这种太不灵活

 

2.父子通信 之 动态数据

父组件的数据将会动态传递给子组件

复制代码
<input v-model="total">
<mime :num-a="total"></mime>

....

//props:['numA']

props:{
   numA:[ String , Number ]  //允许字符串 数字
}
复制代码

这时当input输入什么,子组件的numA将会得到什么

 

3.父子通信 之 子调用父

复制代码
{{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>
复制代码

子组件执行add --> 触发$emit --> 触发父组件increment --> 执行 incrementTotal 方法

 

4.父子通信 之 父调用子

复制代码
<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>
复制代码

通过在子组件上引用ref,从而获得子组件实例,进行相应操作。

 

5.子组件与子组件通信

官网:在简单的场景下,使用一个空的 Vue 实例作为中央事件总线

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

但是这样实在太麻烦了,建议使用vuex

出处http://www.cnblogs.com/QRL909109/p/6166209.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值