vuex引入篇--vue组件间通讯

前言

vue虽然支持双向绑定,可是组件之间总归而言仍是单项的,因此咱们在这一片内容之中将会去简单的了解和总结,咱们最日常的vue组件之间通讯是经过什么样的方式来的。vue

父子组件通讯。

父 --> 子:咱们经常使用的props属性就是用来对父子组件进行内容的传递的。
vuex

父 --> 孙:bash

  • 这里咱们要注意了,咱们能够经过使用props属性来传递。
  • vue为咱们的vueComponent对象提供了$root和 $parent两个属性,分别指向的是根节点的vue对象和父组件的vueComponent对象。这个时候咱们经过这两个对象来进行内容的操做。
  • vue同时为咱们提供了依赖注入功能,经过在组件之中设置provide属性,提供给其后代们以某一份数据或者方法来操做当前组件之中的状态信息。子孙组建须要使用的时候只须要使用inject关键字进行内容的注入,而后咱们能够经过this来调用注入的方法或者参数。代码可见以下
父组件:
methods:{
    sayHello: function(name){
        console.log('this is ' + name + ' saying hello!')
    }
},

provide() {
    return {
        sayHello: this.sayHello
    }
},

mounted() {
    this.sayHello = function(){
        console.log("saying hello after changed");
    }
}
  
子组件:
inject:['sayHello'],

methods: {
    handleInput (event){
        const value = event.target.value;
        this.sayHello("children");
        this.$emit('input', value);
    }
}
复制代码

p.s:这里咱们须要注意一点,使用依赖注入传递的值并非响应式的,因此咱们在父组件之中修改了传递的值的时候,子组件获取的值其实是没有变化以前的。ide

以上三种方式或多或少都确立了传递的结构,使得父子组件之间存在必定的耦合,因此咱们使用这些方式的时候都须要进行必定的考量,依据本身的需求选择通讯的方法。函数


子 --> 父:vue官方推荐的方式是以事件的形式来进行内容的传递。即父组件之中绑定事件函数,留定传递数值的形参,子组件之中经过$emit来调用传递的方法而且传递改变的值信息。上示例:学习

parent.vue:

<template>
  <div>
    <AInput @input="inputEvent" :value="inputContent"/>
    <p>{{ inputContent }}</p>
  </div>
</template>
<script>
import AInput from '@/components/Input.vue'

export default {
  name: "state",
  data () {
    return {
      inputContent: "",
    };
  },
  components: {
    AInput
  },
  methods:{
    inputEvent:function(content){
      this.inputContent = content;
    }
  }
}


children.vue:

<template>
  <input @input="handleInput" :value="value"/>
</template>
<script>
export default {
  name: "inputContent",

  props: {
    value:String
  },

  methods: {
    handleInput (event){
      const value = event.target.value;
      this.sayHello(this.name);
      this.$emit('input', value);
    }
  }
}
复制代码

bus

使用Bus来进行装填管理控制,什么是BUS呢,实际上bus就是一个空的vue对象内容。咱们先来建立一个BUs:ui

import Vue from 'vue'

const Bus = new vue();

Vue.prototype.$bus = Bus;
复制代码

以后咱们能够在每个vue对象之中经过this.$bus来获取到当前的这个bus空对象。并使用它来进行内容的通讯。举一个简单的例子。this

componentOne.vue:

data:() => ({
    content: "check"
}),
methods:{
    passToChild: function(){
        this.$bus.$emit('passTo', this.check);
    }
}


componentTwo.vue:

data:() => ({
    content: "",
}),
mounted() {
    this.$bus.$on('passTo', (content) => {
        this.content = content;
    })    
}
复制代码

这即是BUS的用法。spa


结束:

上面是一些经常使用的组件之间通讯以及状态管理的方式,下一篇文章咱们将会来具体的学习vuex的内容,将会更加方便的管理咱们大型项目之中的状态内容。下章再见。prototype

相关文章
相关标签/搜索