Vue组建通讯

组件的通讯

通讯组件
通常常见的组件之间的通讯有如下几种状况,A和B,B和C,B和D之间都是父子关系,C和D之间是兄弟组件关系。

经常使用的通讯手段有两种:

1.ref:给元素或组件注册引用信息 2.parent/children:访问父级组件和子组件的实例。 这两种方式都是直接经过实例的方式获取的方式。示例以下:vue

//comA组件A
export default {
  data () {
    return {
      title: '测试通讯'
    }
  },
  methods: {
    sayHello () {
      window.alert('你好');
    }
  }
}
复制代码
这里引用组件A
<template>
  <comA ref="comA"></comA>
</template>
<script>
  export default {
    mounted () {
      const comA = this.$refs.comA;
      console.log(comA.title);  // 测试通讯
      comA.sayHello();  // 调用组件comA的方法
    }
  }
</script>
复制代码

上面的例子咱们能够看出咱们使用ref来获取组件的实例上的方法和数据ajax

<div id="count">
    <button @click="showmsg">
      显示两个组件的信息
    </button>
        <child1></child1>
    <child2></child2>
    </div>
<template id="child1">
  <div>
    {{ msg }}
  </div>
</template>
<template id="child2">
  <div>
    {{ msg }}
  </div>
</template>
<script>
    Vue.component('child1', {
      template: '#child1',
      data () {
        return {
          msg: '这是子组件1的信息'
        }
      }
    })
    Vue.component('child2', {
      template: '#child2',
      data () {
        return {
          msg: '这是子组件2的信息'
        }
      }
    })
    new Vue({
      el: '#count',
      data: {
        
      },
      methods: {
        showmsg () {
            for(var i = 0; i < this.$children.length; i++) {
            alert(this.$children[i].msg)
          }
        }
      }
    })
</script>
复制代码

$children 返回全部子组件的实例,是一个数组vuex

<div id="count">
    父组件中的msg: {{ msg }}
        <child1 ref='c1'></child1>
    <child2 ref='c2'></child2>
    </div>
<template id="child1">
  <div>
    {{ msg }}
    <button @click="showpmsg">
      显示父组件msg
    </button>
  </div>
</template>
<template id="child2">
  <div>
    {{ msg }}
  </div>
</template>
<script>
    Vue.component('child1', {
      template: '#child1',
      data () {
        return {
          msg: '这是子组件1的信息'
        }
      },
      methods: {
        showpmsg () {
                alert(this.$parent.msg)
        }
      }
    })
    Vue.component('child2', {
      template: '#child2',
      data () {
        return {
          msg: '这是子组件2的信息'
        }
      }
    })
    new Vue({
      el: '#count',
      data: {
        msg: 'hello parent'
      }
    })
</script>
复制代码

这两种方式是基于组件的上下文环境访问到父组件或者所有子组件(数组)。这种方式有很大的弊端是,没法跨级或兄弟间进行通讯,好比以下的结构数组

// parent.vue
<component-a></component-a>
<component-b></component-b>
<component-c></component-c>
复制代码

咱们假如想在组件A中获取其余组件那么咱们可能须要使用vuex或者和Bus事件总线的方式进行解决。bash

事件总线

定义事件总线的方式有如下两种app

// bus.js 事件总线

import Vue from 'vue'
export const $bus = new Vue()
复制代码
// main.js咱们再main入口中定义这个事件总线
Vue.prototype.$bus = new Vue()
复制代码

发送事件

对下面comA说明,会接收来自父组件的参数number,并显示出来;有个按钮,点击会调用函数handleAddRandom,生成一个随机数,并调用事件总线的$emit方法,将随机数给事件总线,由事件总线进行数据传递。dom

<template>
  <div>
    {{number}}
    <button @click="handleAddRandom">随机增长</button>
  </div>
</template>

<script>
import $bus from ../bus.js
  export default {
    name: "counter",
    props: {
      number: {
        type: Number
      }
    },
    methods: {
      handleAddRandom() {
        const num = Math.floor(Math.random() * 100 + 1);
        console.log("生产的num:" + num);
        this.$bus.$emit('add', num);
      }
    }
  }
</script
复制代码

接收事件

<template>
  <div>
    随机增长:
    <counter :number="number"></counter>
  </div>
</template>

<script>
  import counter from './counter'

  export default {
    name: "index",
    components: {
      counter
    },
    data() {
      return {
        number: 0
      }
    },
    methods: {
      handleAddRandom(num) {
        this.number += num;
      }
    },
    created() {
      //this.$bus.$on须要在created中使用,不然不会生效
      this.$bus.$on('add', this.handleAddRandom);
    },
    beforeDestroy() {
      //须要在beforeDestroy中移除
      this.$bus.$off('add', this.handleAddRandom);
    }
  }
</script>

<style scoped>

</style>
复制代码

上面是咱们经过事件总线的方式进行通讯 而后咱们来讲下另外一种能够媲美Vuex的一种方式provide / injectide

provide / inject

提及这两个API可能你们不太明白咱们来举例子说明函数

// A组件
export default {
  provide: {
    name: 'Aresn'
  }
}

// B组件
export default {
  inject: ['name'],
  mounted () {
    console.log(this.name);  // Aresn
  }
}
复制代码

代码中咱们能够看到咱们再组件A中设置了一个provide:{name:"Aresn"},这个方法的做用就是将该变量提供给全部的子组件。咱们在B组件中咱们使用indect获取了这个变量,这样咱们就可使用this.name获取到这个那么变量。下面咱们可使用一些骚操做大胆的替代Vuex。(这里说明一下官网中不建议咱们是使用这两个API在常规应用程序中,建议使用在高阶组件中,建议归建议用的好就能够啦)测试

使用provide / inject期待Vuex

<template>
  <div>
    <router-view></router-view>
  </div>
</template>
<script>
  export default {

  }
</script>
复制代码

Vue cli中搭建出来的项目结构中都会有一个app.vue做为入口组件,咱们可使用这个API在上面大作文章。

<script>
  export default {
    provide () {
      return {
        app: this
      }
    },
    data () {
      return {
        userInfo: null
      }
    },
    methods: {
      getUserInfo () {
        // 这里经过 ajax 获取用户信息后,赋值给 this.userInfo,如下为伪代码
        $.ajax('/user/info', (data) => {
          this.userInfo = data;
        });
      }
    },
    mounted () {
      this.getUserInfo();
    }
  }
</script>
复制代码

这里咱们把根组件实例做为一个参数传递给app变量,下面咱们就能够经过app[变量||方法]达到vuex的目的

<template>
  <div>
    {{ app.userInfo }}
  </div>
</template>
<script>
  export default {
    inject: ['app'],
    methods: {
      changeUserInfo () {
        // 这里修改完用户数据后,通知 app.vue 更新,如下为伪代码
        $.ajax('/user/update', () => {
          // 直接经过 this.app 就能够调用 app.vue 里的方法
          this.app.getUserInfo();
        })
      }
    }
  }
</script>
复制代码

可是这样作有一个弊端那就是可能会让根组件app.vue的代码变得特别的臃肿,固然也有解决办法,咱们可使用mixins混合的方式将不一样的逻辑分开写到不一样的js里面而后经过 mixins: [mixins_user]的方式在app.vue中引用这个mixin。

相关文章
相关标签/搜索