vue组件之间通信的8种方式

对于vue来说,组件之间的消息传递是非常重要的,下面是我对组件之间消息传递的常用方式的总结。

  • props和$emit(常用)
  • $attrs和$listeners
  • 中央事件总线(非父子组件间通信)
  • v-model
  • provide和inject
  • $parent和$children
  • vuex

1.props和$emit

   父组件向子组件传递数据是通过prop传递的,子组件传递数据给父组件是通过$emit触发事件来做到的.

 1 Vue.component('child',{
 2     data(){
 3       return {
 4         mymessage:this.message
 5       }
 6     },
 7     template:`
 8       <div>
 9         <input type="text" v-model="mymessage" @input="passData(mymessage)"> </div>
10     `,
11     props:['message'],//设置props属性值,得到父组件传递过来的数据
12     methods:{
13       passData(val){
14         //触发父组件中的事件,向父组件传值
15         this.$emit('getChildData',val)
16       }
17     }
18   })
19   Vue.component('parent',{
20     template:`
21       <div>
22         <p>this is parent compoent!</p>
23         <child :message="message" v-on:getChildData="getChildData"></child>
24       </div>
25     `,
26     data(){
27       return {
28         message:'hello'
29       }
30     },
31     methods:{
32       //执行子组件触发的事件
33       getChildData(val){
34         console.log(val)
35       }
36     }
37   })

 在上面的例子中,有父组件parent和子组件child。

  1).父组件传递了message数据给子组件,并且通过v-on绑定了一个getChildData事件来监听子组件的触发事件;

  2).子组件通过props得到相关的message数据,最后通过this.$emit触发了getChildData事件

2.$attrs和$listeners

  第一种方式处理父子组件之间的数据传输有一个问题:如果父组件A下面有子组件B,组件B下面有组件C,这时如果组件A想传递数据给组件C怎么办呢? 如果采用第一种方法,我们必须让组件A通过prop传递消息给组件B,组件B在通过prop传递消息给组件C;要是组件A和组件C之间有更多的组件,那采用这种方式就很复杂了。Vue 2.4开始提供了$attrs和$listeners来解决这个问题,能够让组件A之间传递消息给组件C。

 1 Vue.component('C',{
 2     template:`
 3       <div>
 4         <input type="text" v-model="$attrs.messagec" @input="passCData($attrs.messagec)"> </div>
 5     `,
 6     methods:{
 7       passCData(val){
 8         //触发父组件A中的事件
 9         this.$emit('getCData',val)
10       }
11     }
12   })
13   Vue.component('B',{
14     data(){
15       return {
16         mymessage:this.message
17       }
18     },
19     template:`
20       <div>
21         <input type="text" v-model="mymessage" @input="passData(mymessage)">
22         <!-- C组件中能直接触发getCData的原因在于 B组件调用C组件时 使用 v-on 绑定了$listeners 属性 -->
23         <!-- 通过v-bind 绑定$attrs属性,C组件可以直接获取到A组件中传递下来的props(除了B组件中props声明的) -->
24         <C v-bind="$attrs" v-on="$listeners"></C>
25       </div>
26     `,
27     props:['message'],//得到父组件传递过来的数据
28     methods:{
29       passData(val){
30         //触发父组件中的事件
31         this.$emit('getChildData',val)
32       }
33     }
34   })
35   Vue.component('A',{
36     template:`
37       <div>
38         <p>this is parent compoent!</p>
39         <B :messagec="messagec" :message="message" v-on:getCData="getCData" v-on:getChildData="getChildData(message)"></B>
40       </div>
41     `,
42     data(){
43       return {
44         message:'hello',
45         messagec:'hello c' //传递给c组件的数据
46       }
47     },
48     methods:{
49       getChildData(val){
50         console.log('这是来自B组件的数据')
51       },
52       //执行C子组件触发的事件
53       getCData(val){
54         console.log("这是来自C组件的数据:"+val)
55       }
56     }
57   })

 3. 中央事件总线

上面两种方式处理的都是父子组件之间的数据传递,而如果两个组件不是父子关系呢?这种情况下可以使用中央事件总线的方式。新建一个Vue事件bus对象,然后通过bus.$emit触发事件,bus.$on监听触发的事件。

Vue.component('brother1',{
    data(){
      return {
        mymessage:'hello brother1'
      }
    },
    template:`
      <div>
        <p>this is brother1 compoent!</p>
        <input type="text" v-model="mymessage" @input="passData(mymessage)">
      </div>
    `,
    methods:{
      passData(val){
        //触发全局事件globalEvent
        bus.$emit('globalEvent',val)
      }
    }
  })
  Vue.component('brother2',{
    template:`
      <div>
        <p>this is brother2 compoent!</p>
        <p>brother1传递过来的数据:{{brothermessage}}</p>
      </div>
    `,
    data(){
      return {
        mymessage:'hello brother2',
        brothermessage:''
      }
    },
    mounted(){
      //绑定全局事件globalEvent
      bus.$on('globalEvent',(val)=>{
        this.brothermessage=val;
      })
    }
  })
  //中央事件总线
  var bus=new Vue();
  var app=new Vue({
    el:'#app',
    template:`
      <div>
        <brother1></brother1>
        <brother2></brother2>
      </div>
    `
  })

4. provide和inject

  在 Vue.js 的 2.2.0+ 版本中添加加了 provide 和 inject 选项。他们成对出现,用于父级组件向下传递数据。

父组件中通过provider来提供变量,然后在子组件中通过inject来注入变量。不论子组件有多深,只要调用了inject那么就可以注入provider中的数据。而不是局限于只能从当前父组件的prop属性来获取数据,只要在父组件的生命周期内,子组件都可以调用。

 1 Vue.component('child',{
 2     inject:['for'],//得到父组件传递过来的数据
 3     data(){
 4       return {
 5         mymessage:this.for
 6       }
 7     },
 8     template:`
 9       <div>
10         <input type="tet" v-model="mymessage">
11       </div>
12   })
13   Vue.component('parent',{
14     template:`
15       <div>
16         <p>this is parent compoent!</p>
17         <child></child>
18       </div>
19     `,
20     provide:{
21       for:'test'
22     },
23     data(){
24       return {
25         message:'hello'
26       }
27     }
28   })

5. v-model

  父组件通过v-model传递值给子组件时,会自动传递一个value的prop属性,在子组件中通过this.$emit(‘input',val)自动修改v-model绑定的值

Vue.component('child',{
    props:{
      value:String, //v-model会自动传递一个字段为value的prop属性
    },
    data(){
      return {
        mymessage:this.value
      }
    },
    methods:{
      changeValue(){
        this.$emit('input',this.mymessage);//通过如此调用可以改变父组件上v-model绑定的值
      }
    },
    template:`
      <div>
        <input type="text" v-model="mymessage" @change="changeValue">
      </div>
  })
  Vue.component('parent',{
    template:`
      <div>
        <p>this is parent compoent!</p>
        <p>{{message}}</p>
        <child v-model="message"></child>
      </div>
    `,
    data(){
      return {
        message:'hello'
      }
    }
  })
  var app=new Vue({
    el:'#app',
    template:`
      <div>
        <parent></parent>
      </div>
    `
  })

 6. $parent和$children

      在组件内部可以直接通过子组件$parent对父组件进行操作,父组件通过$children对子组件进行操作.

Vue.component('child',{
    props:{
      value:String, //v-model会自动传递一个字段为value的prop属性
    },
    data(){
      return {
        mymessage:this.value
      }
    },
    methods:{
      changeValue(){
        this.$parent.message = this.mymessage;//通过如此调用可以改变父组件的值
      }
    },
    template:`
      <div>
        <input type="text" v-model="mymessage" @change="changeValue">
      </div>
  })
  Vue.component('parent',{
    template:`
      <div>
        <p>this is parent compoent!</p>
        <button @click="changeChildValue">test</button >
        <child></child>
      </div>
    `,
    methods:{
      changeChildValue(){
        this.$children[0].mymessage = 'hello';
      }
    },
    data(){
      return {
        message:'hello'
      }
    }
  })
  var app=new Vue({
    el:'#app',
    template:`
      <div>
        <parent></parent>
      </div>
    `
  })

7. vuex处理组件之间的数据交互

如果业务逻辑复杂,很多组件之间需要同时处理一些公共的数据,这个时候才有上面这一些方法可能不利于项目的维护,vuex的做法就是将这一些公共的数据抽离出来,然后其他组件就可以对这个公共数据进行读写操作,这样达到了解耦的目的。

 参考链接:https://my.oschina.net/u/3982182/blog/3019264

猜你喜欢

转载自www.cnblogs.com/barryzhang/p/10566515.html