Home  >  Article  >  Web Front-end  >  [Summary] 11 communication methods of Vue components

[Summary] 11 communication methods of Vue components

青灯夜游
青灯夜游forward
2023-04-18 17:03:291177browse

How to communicate between Vue components? The following article summarizes 11 communication methods of Vue components. I hope it will be helpful to you!

[Summary] 11 communication methods of Vue components

Components are one of the most powerful features of vue.js, and the scopes of component instances are independent of each other, which means that between different components The data cannot reference each other. There are various methods of value transfer between Vue components, which are not limited to parent-child value transfer and event value transfer.

provide / inject

This set of options needs to be used together to allow an ancestor component to inject an Dependencies, no matter how deep the component hierarchy is, are always effective as long as the upstream and downstream relationships are established. [Related recommendations: vuejs video tutorial, web front-end development]

// provide 选项应该是一个对象或返回一个对象的函数
// inject 选项应该是:一个字符串数组,或一个对象,对象的 key 是本地的绑定名

// 父级组件提供 'foo'
var Provider = {
  provide: {
    foo: 'bar'
  },
  // ...
}

// 子组件注入 'foo' (数组形式)
var Child = {
  inject: ['foo'], 
  created () {
    console.log(this.foo) // => "bar"
  }
  // ...
}

或 (对象形式)
var Child = {
  inject: {
  	foo: { 
  		from: 'bar', // 可选
  		default: 'self defined content' // 默认值
  	}
  }, 
  created () {
    console.log(this.foo) // => "bar"
  }
  // ...
}

It should be noted that: in Vue 2.2.1 or later versions, the value injected by inject Will get

// 使用一个注入的值作为数据(data)的入口 或者 属性(props)的默认值
const Child = {
  inject: ['foo'],
  data () {
    return {
      bar: this.foo // 输出bar的值与foo相同
    }
  }
}

const Child = {
  inject: ['foo'],
  props: {
    bar: {
      default () {
        return this.foo
      }
    }
  }
}

-----------------------------------------------------------------------------------------------
// 注入可以通过设置默认值使其变成可选项
const Child = {
  inject: {
    foo: { // 注意: 此处key值必须是父组件中provide的属性的key
      from: 'bar', // 属性是在可用的注入内容中搜索用的 key (字符串或 Symbol), data或者props中的可搜索值
      default: 'foo' // 属性是降级情况下使用的 value, 默认值为 ‘foo’
    }
  }
}

// 与 prop 的默认值类似
const Child = {
  inject: {
    foo: {
      from: 'bar',
      default: () => [1, 2, 3] // 默认值为引用类型时,需要使用一个工厂方法返回对象
    }
  }
}

IntroductionVue2.2.0 new API before props and data are initialized. This pair of options needs to be used together to allow an ancestor component to inject a dependency into all its descendants. No matter how deep the component hierarchy is, it will always take effect when the upstream and downstream relationships are established. In a nutshell: Provide variables through provider in ancestor components, and then inject variables through inject in descendant components. The provide / inject API mainly solves the communication problem between cross-level components, but its usage scenario is mainly for sub-components to obtain the status of superior components, and a relationship between active provision and dependency injection is established between cross-level components.

CaseSuppose there are two components: A.vue and B.vue, B is a subcomponent of A

A.vue

export default {
  provide: {
    name: '浪里行舟'
  }
}

B .vue

export default {
  inject: ['name'],
  mounted () {
    console.log(this.name);  // 浪里行舟
  }
}

As you can see, in A.vue, we set up a provide: name, with the value of "Langli sailing boat". Its function is to provide the name variable to all its sub-components. In B.vue, the name variable provided from component A is injected through inject. Then in component B, you can directly access this variable through this.name, and its value is also the same. This is the core usage of provide / inject API.

It should be noted that the provide and inject bindings are not responsive. This is intentional. However, if you pass in a listenable object, the properties of the object are still responsive----vue official documentation Therefore, if the name of A.vue changes above, this.name of B.vue will not change, and it will still be sailing in the waves.

How to implement data responsiveness with provide and inject

Generally speaking, there are two methods:

  • provide instances of ancestor components, Then inject dependencies into the descendant component, so that you can directly modify the properties of the instance of the ancestor component in the descendant component. However, this method has the disadvantage that many unnecessary things such as props and methods are mounted on this instance.
  • Use the latest API Vue.observable in 2.6 to optimize the responsive provide (recommended)

Let’s take a look at an example: Sun components D, E and F get the color value passed by component A and can implement it Data changes responsively, that is, after the color of component A changes, components D, E, and F will not change accordingly (the core code is as follows:)

A component

<div>
      <h1>A 组件</h1>
      <button @click="() => changeColor()">改变color</button>
      <ChildrenB />
      <ChildrenC />
</div>
......
  data() {
    return {
      color: "blue"
    };
  },
  // provide() {
  //   return {
  //     theme: {
  //       color: this.color //这种方式绑定的数据并不是可响应的
  //     } // 即A组件的color变化后,组件D、E、F不会跟着变
  //   };
  // },
  provide() {
    return {
      theme: this//方法一:提供祖先组件的实例
    };
  },
  methods: {
    changeColor(color) {
      if (color) {
        this.color = color;
      } else {
        this.color = this.color === "blue" ? "red" : "blue";
      }
    }
  }
  // 方法二:使用2.6最新API Vue.observable 优化响应式 provide
  // provide() {
  //   this.theme = Vue.observable({
  //     color: "blue"
  //   });
  //   return {
  //     theme: this.theme
  //   };
  // },
  // methods: {
  //   changeColor(color) {
  //     if (color) {
  //       this.theme.color = color;
  //     } else {
  //       this.theme.color = this.theme.color === "blue" ? "red" : "blue";
  //     }
  //   }
  // }

F component

<template functional>
  <div class="border2">
    <h3 :style="{ color: injections.theme.color }">F 组件</h3>
  </div>
</template>
<script>
export default {
  inject: {
    theme: {
      //函数式组件取值不一样
      default: () => ({})
    }
  }
};
</script>

Although provide and inject mainly provide use cases for high-end plug-ins/component libraries, if you can use them skillfully in business, you can achieve twice the result with half the effort!

props (passed from parent to child)

// 创建组件
Vue.component(&#39;props-demo-advanced&#39;, {
  props: {
    age: {
      type: Number,
      default: 0
    }
  }
})

// 父组件中注册和使用组件,并传值
<props-demo-advanced :age="age"> </props-demo-advanced>

props/$emitParent component A Pass to sub-component B through props, and B to A is achieved through $emit in component B and v-on in component A. Case: Parent component passes value to child component The following example shows how the parent component passes values ​​to the child component: How to obtain the data in the parent component App.vue in the child component Users.vueusers:["Henry","Bucky","Emily"]

App.vue parent component

<template>
  <div id="app">
    <users v-bind:users="users"></users>//前者自定义名称便于子组件调用,后者要传递数据名
  </div>
</template>
<script>
import Users from "./components/Users"
export default {
  name: &#39;App&#39;,
  data(){
    return{
      users:["Henry","Bucky","Emily"]
    }
  },
  components:{
    "users":Users
  }
}

users subcomponent

<template>
  <div class="hello">
    <ul>
      <li v-for="user in users">{{user}}</li>//遍历传递过来的值,然后呈现到页面
    </ul>
  </div>
</template>
<script>
export default {
  name: &#39;HelloWorld&#39;,
  props:{
    users:{           //这个就是父组件中子标签自定义名字
      type:Array,
      required:true
    }
  }
}
</script>

Summary: The parent component passes data downward to the child component through props. Note: There are three forms of data in the component: data, props, computed

$emit (pass from son to father)

// 子组件Child, 负载payload可选
this.$emit(&#39;eventName&#39;, payload)

// 父组件 Parent
<Parent @evnetName="sayHi"></Parent>

Case: Child component passes value to parent component (through event form) The following example illustrates how a subcomponent passes a value to a parent component: after clicking "Vue.js Demo", the subcomponent passes a value to the parent component, and the text changes from "A value is passed" to "The child passes a value to the parent component." ” to realize the transfer of value from the child component to the parent component.

Subcomponent

<template>
  <header>
    <h1 @click="changeTitle">{{title}}</h1>//绑定一个点击事件
  </header>
</template>
<script>
export default {
  name: &#39;app-header&#39;,
  data() {
    return {
      title:"Vue.js Demo"
    }
  },
  methods:{
    changeTitle() {
      this.$emit("titleChanged","子向父组件传值");//自定义事件  传递值“子向父组件传值”
    }
  }
}
</script>

Parent component

<template>
  <div id="app">
    <app-header v-on:titleChanged="updateTitle" ></app-header>//与子组件titleChanged自定义事件保持一致
   // updateTitle($event)接受传递过来的文字
    <h2>{{title}}</h2>
  </div>
</template>
<script>
import Header from "./components/Header"
export default {
  name: &#39;App&#39;,
  data(){
    return{
      title:"传递的是一个值"
    }
  },
  methods:{
    updateTitle(e){   //声明这个函数
      this.title = e;
    }
  },
  components:{
   "app-header":Header,
  }
}
</script>

Summary: The subcomponent sends messages to the parent component through events. In fact, the subcomponent sends its own Data is sent to the parent component.

$emit/$on这种方法通过一个空的Vue实例作为中央事件总线(事件中心),用它来触发事件和监听事件,巧妙而轻量地实现了任何组件间的通信,包括父子、兄弟、跨级。当我们的项目比较大时,可以选择更好的状态管理解决方案vuex。

1.具体实现方式:

var Event=new Vue();
Event.$emit(事件名,数据);
Event.$on(事件名,data => {});

案例 : 假设兄弟组件有三个,分别是A、B、C组件,C组件如何获取A或者B组件的数据

<div id="itany">
	<my-a></my-a>
	<my-b></my-b>
	<my-c></my-c>
</div>
<template id="a">
  <div>
    <h3>A组件:{{name}}</h3>
    <button @click="send">将数据发送给C组件</button>
  </div>
</template>
<template id="b">
  <div>
    <h3>B组件:{{age}}</h3>
    <button @click="send">将数组发送给C组件</button>
  </div>
</template>
<template id="c">
  <div>
    <h3>C组件:{{name}},{{age}}</h3>
  </div>
</template>
<script>
var Event = new Vue();//定义一个空的Vue实例
var A = {
	template: &#39;#a&#39;,
	data() {
	  return {
	    name: &#39;tom&#39;
	  }
	},
	methods: {
	  send() {
	    Event.$emit(&#39;data-a&#39;, this.name);
	  }
	}
}
var B = {
	template: &#39;#b&#39;,
	data() {
	  return {
	    age: 20
	  }
	},
	methods: {
	  send() {
	    Event.$emit(&#39;data-b&#39;, this.age);
	  }
	}
}
var C = {
	template: &#39;#c&#39;,
	data() {
	  return {
	    name: &#39;&#39;,
	    age: ""
	  }
	},
	mounted() {//在模板编译完成后执行
	Event.$on(&#39;data-a&#39;,name => {
	     this.name = name;//箭头函数内部不会产生新的this,这边如果不用=>,this指代Event
	})
	Event.$on(&#39;data-b&#39;,age => {
	     this.age = age;
	})
	}
}
var vm = new Vue({
	el: &#39;#itany&#39;,
	components: {
	  &#39;my-a&#39;: A,
	  &#39;my-b&#39;: B,
	  &#39;my-c&#39;: C
	}
});	
</script>

$on 监听了自定义事件 data-a和data-b,因为有时不确定何时会触发事件,一般会在 mounted 或 created 钩子中来监听。

eventBus(全局创建Vue实例)

进行事件监听和数据传递。同时vuex也是基于这个原理实现的

// 三步使用
// 1. 创建
window.$bus = new Vue()

// 2. 注册事件
window.$bus.$on(&#39;user_task_change&#39;, (payload) => {
  console.log(&#39;事件触发&#39;)
})

// 3. 触发
window.$bus.$emit(&#39;user_task_change&#39;, payload)

vuex (状态管理)

1.简要介绍Vuex原理Vuex实现了一个单向数据流,在全局拥有一个State存放数据,当组件要更改State中的数据时,必须通过Mutation进行,Mutation同时提供了订阅者模式供外部插件调用获取State数据的更新。而当所有异步操作(常见于调用后端接口异步获取更新数据)或批量的同步操作需要走Action,但Action也是无法直接修改State的,还是需要通过Mutation来修改State的数据。最后,根据State的变化,渲染到视图上。

2.简要介绍各模块在流程中的功能

  • Vue Components:Vue组件。HTML页面上,负责接收用户操作等交互行为,执行dispatch方法触发对应action进行回应。
  • dispatch:操作行为触发方法,是唯一能执行action的方法。
  • actions:操作行为处理模块,由组件中的$store.dispatch('action 名称', data1)来触发。然后由commit()来触发mutation的调用 , 间接更新 state。负责处理Vue Components接收到的所有交互行为。包含同步/异步操作,支持多个同名方法,按照注册的顺序依次触发。向后台API请求的操作就在这个模块中进行,包括触发其他action以及提交mutation的操作。该模块提供了Promise的封装,以支持action的链式触发。
  • commit:状态改变提交操作方法。对mutation进行提交,是唯一能执行mutation的方法。
  • mutations:状态改变操作方法,由actions中的commit('mutation 名称')来触发。是Vuex修改state的唯一推荐方法。该方法只能进行同步操作,且方法名只能全局唯一。操作之中会有一些hook暴露出来,以进行state的监控等。
  • state:页面状态管理容器对象。集中存储Vue components中data对象的零散数据,全局唯一,以进行统一的状态管理。页面显示所需的数据从该对象中进行读取,利用Vue的细粒度数据响应机制来进行高效的状态更新。
  • getters:state对象读取方法。图中没有单独列出该模块,应该被包含在了render中,Vue Components通过该方法读取全局state对象。

3.Vuex与localStoragevuex 是 vue 的状态管理器,存储的数据是响应式的。但是并不会保存起来,刷新之后就回到了初始状态,具体做法应该在vuex里数据改变的时候把数据拷贝一份保存到localStorage里面,刷新之后,如果localStorage里有保存的数据,取出来再替换store里的state。

let defaultCity = "上海"
try {   // 用户关闭了本地存储功能,此时在外层加个try...catch
  if (!defaultCity){
    defaultCity = JSON.parse(window.localStorage.getItem(&#39;defaultCity&#39;))
  }
}catch(e){}
export default new Vuex.Store({
  state: {
    city: defaultCity
  },
  mutations: {
    changeCity(state, city) {
      state.city = city
      try {
      window.localStorage.setItem(&#39;defaultCity&#39;, JSON.stringify(state.city));
      // 数据改变的时候把数据拷贝一份保存到localStorage里面
      } catch (e) {}
    }
  }
})

这里需要注意的是:由于vuex里,我们保存的状态,都是数组,而localStorage只支持字符串,所以需要用JSON转换:

JSON.stringify(state.subscribeList);   // array -> string
JSON.parse(window.localStorage.getItem("subscribeList"));    // string -> array

Vuex文件 案例 : 目录结构如下:

[Summary] 11 communication methods of Vue components

其中vuex相关的三个文件counts.js、 index.js、 operate.js,内容如下:

[Summary] 11 communication methods of Vue components

index.js

import Vue from &#39;vue&#39;
import Vuex from &#39;vuex&#39;
import counter from &#39;./counter.js&#39;
import operate from &#39;./operate.js&#39;
Vue.use(Vuex)

const state = {
  name: &#39;zhaoyh&#39;
}

const getters = {
  getName (state) {
    return state.name
  }
}

const mutations = {
  changeName (state, payload) {
    state.name = `${state.name} ${payload}`
  }
}

const actions = {
  changeNameAsync (context, payload) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        context.commit(&#39;changeName&#39;, payload)
      }, 1000)
    })
  }
}

const store = new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
  modules: {
    counter,
    operate
  }
})

export default store

counter.js

// 模块内方法调用本模块内的方法和数据
const state = {
  counterName: &#39;module > counter > zhaoyh&#39;
}
const getters = {
  // state, getters: 本模块内的state, getters
  // rootState, rootGetters: 根模块/根节点内的state, getters
  // rootState, rootGetters: 同时也包括各个模块中的state 和 getters
  getCounterName (state, getters, rootState, rootGetters) {
    // rootState.name
    // rootState.counter.counterName
    // rootState.operate.operateName
    console.log(rootState)
    // rootGetters.getName, 
    // rootGetters[&#39;counter/getCounterName&#39;]
    // rootGetters[&#39;operate/getOperateName&#39;]
    console.log(rootGetters)
    return state.counterName
  }
}
const mutations = {
  changeCounterName (state, payload) {
    state.counterName = `${state.counterName} ${payload}`
  }
}
const actions = {
  // context 与 store 实例具有相同方法和属性 ------  important!!!
  // context 包括: dispatch, commit, state, getters, rootState, rootGetters
  changeCounterNameAsync (context, payload) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {context.commit(&#39;changeCounterName&#39;, payload)}, 1000)
    })
  }
}
export default {
  // 注意此处是namespaced,而不是namespace,
  // 写错的话程序不会报错,vuex静默无法正常执行
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}

operate.js

// 模块内方法调用和获取本模块之外的方法和数据
const state = {
  operateName: &#39;module > operate > zhaoyh&#39;
}
// 如果你希望使用全局 state 和 getter
// rootState 和 rootGetter 会作为第三和第四参数传入
// 也会通过 context 对象的属性传入 action
const getters = {
  // state, getters: 本模块内的state, getters
  // rootState, rootGetters: 根模块/根节点内的state, getters, 包括各个模块中的state 和 getters
  getOperateName (state, getters, rootState, rootGetters) {
    return state.operateName
  }
}
const mutations = {
  operateChangeCounterName (state, payload) {
    state.counterName = `${state.counterName} ${payload}`
  }
}
// 如果你希望使用全局 state 和 getter,
// 也会通过 context 对象的属性传入 action
const actions = {
  // context 与 store 实例具有相同方法和属性---- !!important!!!
  // context 包括:
  // dispatch, commit, state, getters, rootState, rootGetters
  operateChangeCounterNameAsync (context, payload) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
	    /*
	      * 若需要在全局命名空间内分发 action 或提交 mutation,
	      * 将 {root: true} 作为第三参数传给 dispatch 或 commit 即可
	    */
	      context.commit(&#39;counter/changeCounterName&#39;, payload, { root: true })
	      // 或 context.dispatch(&#39;counter/changeCounterNameAsync&#39;, null, { root: true })
      }, 1000)
    })
  }
}
export default {
  // 注意此处是namespaced,而不是namespace,
  // 写错的话程序不会报错,vuex静默无法正常执行
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}

vuex属性、方法的引用方式: common-operate.vue

<template>
  <div>
    <h2>{{title}}</h2>
    <ul>
      <li>name: {{name}}</li>
      <li>getName: {{getName}}</li>
      <li><button @click="changeName(&#39;lastName&#39;)">Mutation操作</button></li>
      <li><button @click="changeNameAsync(&#39;lastName&#39;)">Action操作</button></li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions, mapMutations } from &#39;vuex&#39;
export default {
  data () {
    return {
      title: &#39;vuex常规操作1&#39;
    }
  },
  computed: {
    ...mapState([&#39;name&#39;]),
    ...mapGetters([&#39;getName&#39;])
  },
  methods: {
    ...mapMutations([&#39;changeName&#39;]),
    ...mapActions([&#39;changeNameAsync&#39;])
  }
}
</script>

<style scoped>
ul, li{
  padding: 0;
  margin: 0;
  padding: 8px 15px;
}
</style>

common-operate2.vue

<template>
  <div>
    <h2>{{title}}</h2>
    <ul>
      <li>name: {{name}}</li>
      <li>getName: {{getName}}</li>
      <li><button @click="changeName(&#39;lastName&#39;)">Mutation操作</button></li>
      <li><button @click="changeNameAsync(&#39;lastName&#39;)">Action操作</button></li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapGetters } from &#39;vuex&#39;
export default {
  data () {
    return {
      title: &#39;vuex常规操作2&#39;
    }
  },
  computed: {
    ...mapState([&#39;name&#39;]),
    ...mapGetters([&#39;getName&#39;])
  },
  methods: {
    // mutation
    changeName () {
      this.$store.commit(&#39;changeName&#39;, &#39;lastName&#39;)
    },
    // actions
    changeNameAsync () {
      this.$store.dispatch(&#39;changeNameAsync&#39;, &#39;lastName&#39;)
    }
  }
}
</script>

<style scoped>
ul, li{
  padding: 0;
  margin: 0;
  padding: 8px 15px;
}
</style>

module-operate.vue

<template>
  <div>
    <h2>{{title}}</h2>
    <ul>
      <li>name: {{counterName}}</li>
      <li>getName: {{getCounterName}}</li>
      <li><button @click="changeName(&#39;lastName&#39;)">Mutation操作</button></li>
      <li><button @click="changeNameAsync(&#39;lastName&#39;)">Action操作</button></li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapGetters } from &#39;vuex&#39;
export default {
  data () {
    return {
      title: &#39;模块的基本操作方法&#39;
    }
  },
  computed: {
    ...mapState(&#39;counter&#39;, [&#39;counterName&#39;]),
    ...mapGetters(&#39;counter&#39;, [&#39;getCounterName&#39;])
  },
  methods: {
    // mutation
    changeName () {
      this.$store.commit(&#39;counter/changeCounterName&#39;, &#39;lastName&#39;)
    },
    // actions
    changeNameAsync () {
      this.$store.dispatch(&#39;counter/changeCounterNameAsync&#39;, &#39;lastName&#39;)
    }
  }
}
</script>

<style scoped>
ul, li{
  padding: 0;
  margin: 0;
  padding: 8px 15px;
}
</style>

module-operate2.vue

<template>
  <div>
    <h2>{{title}}</h2>
    <ul>
      <li>name: {{counterName}}</li>
      <li>getName: {{getCounterName}}</li>
      <li><button @click="changeCounterName(&#39;lastName&#39;)">Mutation操作</button></li>
      <li><button @click="changeCounterNameAsync(&#39;lastName&#39;)">Action操作</button></li>
      <li><button @click="rename(&#39;rename&#39;)">Action操作</button></li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from &#39;vuex&#39;
export default {
  data () {
    return {
      title: &#39;模块内方法调用本模块内内的方法和数据&#39;
    }
  },
  computed: {
    ...mapState(&#39;counter&#39;, [&#39;counterName&#39;]),
    ...mapGetters(&#39;counter&#39;, [&#39;getCounterName&#39;])
  },
  methods: {
    ...mapMutations(&#39;counter&#39;, [&#39;changeCounterName&#39;]),
    ...mapActions(&#39;counter&#39;, [&#39;changeCounterNameAsync&#39;]),
    // 多模块方法引入的方法名重命名
    ...mapActions(&#39;counter&#39;, {
      rename: &#39;changeCounterNameAsync&#39;
    }),
    otherMethods () {
      console.log(&#39;继续添加其他方法。&#39;)
    }
  }
}
</script>

<style scoped>
ul, li{
  padding: 0;
  margin: 0;
  padding: 8px 15px;
}
</style>

module-operate3.vue

<template>
  <div>
    <h2>{{title}}</h2>
    <ul>
      <li>name: {{counterName}}</li>
      <li>getName: {{getCounterName}}</li>
      <li><button @click="operateChangeCounterNameAsync(&#39;operate lastName&#39;)">Action操作</button></li>
    </ul>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from &#39;vuex&#39;
export default {
  data () {
    return {
      title: &#39;模块内方法调用和获取本模块之外的方法和数据&#39;
    }
  },
  computed: {
    ...mapState(&#39;counter&#39;, [&#39;counterName&#39;]),
    ...mapGetters(&#39;counter&#39;, [&#39;getCounterName&#39;])
  },
  methods: {
    ...mapMutations(&#39;operate&#39;, [&#39;operateChangeCounterName&#39;]),
    ...mapActions(&#39;operate&#39;, [&#39;operateChangeCounterNameAsync&#39;]),
    otherMethods () {
      console.log(&#39;继续添加其他方法。&#39;)
    }
  }
}
</script>

<style scoped>
ul, li{
  padding: 0;
  margin: 0;
  padding: 8px 15px;
}
</style>

###### $parent / $children / $refs (获取组件实例)$refs 获取对应组件实例,如果是原生dom,那么直接获取的是该dom$parent / $children 该属性只针对vue组件,获取父/子组件实例 注: 节制地使用$parent $children - 它们的主要目的是作为访问组件的应急方法。更推荐用 props 和 events 实现父子组件通信

<!--  父组件,HelloWorld.vue-->
<template>
  <div class="hello">
    <ipc ref="ipcRef"></ipc>
  </div>
</template>

<script>
import ipc from &#39;./ipc&#39;
export default {
  name: &#39;HelloWorld&#39;,
  data () {
    return {
      parentVal: &#39;parent content&#39;
    }
  },
  mounted () {
    console.log(this.$refs.ipcRef.$data.child1) // "child1 content"
    console.log(this.$children[0].$data.child2) // "child2 content"
  },
  components: {
    ipc
  }
}
</script>
<!-- 子组件, ipc.vue-->
<template>
  <div>
  </div>
</template>

<script>
export default {
  props: {
  },
  data () {
    return {
      child1: &#39;child1 content&#39;,
      child2: &#39;child2 content&#39;
    }
  },
  mounted () {
    console.log(this.$parent.parentVal) // "parent content"
  }
}
</script>

ref:如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件实例$parent / $children:访问父 / 子实例

需要注意的是:这两种都是直接得到组件实例,使用后可以直接调用组件的方法或访问数据。我们先来看个用 ref来访问组件的例子:

component-a 子组件

export default {
  data () {
    return {
      title: &#39;Vue.js&#39;
    }
  },
  methods: {
    sayHello () {
      window.alert(&#39;Hello&#39;);
    }
  }
}

父组件

<template>
  <component-a ref="comA"></component-a>
</template>
<script>
  export default {
    mounted () {
      const comA = this.$refs.comA;
      console.log(comA.title);  // Vue.js
      comA.sayHello();  // 弹窗
    }
  }
</script>

不过,这两种方法的弊端是,无法在跨级或兄弟间通信。

parent.vue

<component-a></component-a>
<component-b></component-b>
<component-b></component-b>

我们想在 component-a 中,访问到引用它的页面中(这里就是 parent.vue)的两个 component-b 组件,那这种情况下,就得配置额外的插件或工具了,比如 Vuex 和 Bus 的解决方案。

多级组件嵌套需要传递数据时,通常使用的方法是通过vuex。但如果仅仅是传递数据,而不做中间处理,使用 vuex 处理,未免有点大材小用。为此Vue2.4 版本提供了另一种方法----$attrs/$listeners

$attrs:包含了父作用域中不被 prop 所识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs" 传入内部组件。通常配合 inheritAttrs 选项一起使用。

$listeners:包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件

$attrs

1) 包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外) 2) 当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外) 可以通过v-bind="$attrs" 将所有父作用域的绑定 (class、style、 ref 除外) 传入内部组件注: 在创建高级别的组件时非常有用

根组件HelloWorld.vue 中引入 ipc.vue

<ipc
   koa="ipcRef"
   name="go"
   id="id"
   ref="ref"
   style="border: 1px solid red;"
   class="className"
   >
</ipc>

ipc.vue  中引入 ipcChild.vue

<template>
  <div>
    <ipcChild v-bind="$attrs" selfDefine="selfDefine"></ipcChild>
  </div>
</template>

<script>
import ipcChild from &#39;./ipcChild&#39;
export default {
  components: {
    ipcChild
  },
  mounted () {
    console.log(this.$attrs) // {id: "id", name: "go", koa: "ipcRef"}
  }
}
</script>

// ipcChild.vue中打印接收到的$attrs

<script>
export default {
  created () {
    console.log(this.$attrs) // "{"selfDefine":"selfDefine","koa":"ipcRef","name":"go","id":"id"}"
  }
}
</script>

$listeners

包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器 通过 v-on="$listeners" 将父作用域的时间监听器传入内部组件

A、B、C三个组件依次嵌套, B嵌套在A中,C嵌套在B中。 借助 B 组件的中转,从上到下props依次传递,从下至上,$emit事件的传递,达到跨级组件通信的效果。$attrs以及$listeners 的出现解决的的问题,B 组件在其中传递props以及事件的过程中,不必在写多余的代码,仅仅是将 $attrs以及$listeners 向上或者向下传递即可。

跨级通信的案例

index.vue

<template>
  <div>
    <h2>浪里行舟</h2>
    <child-com1
      :foo="foo"
      :boo="boo"
      :coo="coo"
      :doo="doo"
      title="前端工匠"
    ></child-com1>
  </div>
</template>
<script>
const childCom1 = () => import("./childCom1.vue");
export default {
  components: { childCom1 },
  data() {
    return {
      foo: "Javascript",
      boo: "Html",
      coo: "CSS",
      doo: "Vue"
    };
  }
};
</script>

childCom1.vue

<template class="border">
  <div>
    <p>foo: {{ foo }}</p>
    <p>childCom1的$attrs: {{ $attrs }}</p>
    <child-com2 v-bind="$attrs"></child-com2>
  </div>
</template>
<script>
const childCom2 = () => import("./childCom2.vue");
export default {
  components: {
    childCom2
  },
  inheritAttrs: false, // 可以关闭自动挂载到组件根元素上的没有在props声明的属性
  props: {
    foo: String // foo作为props属性绑定
  },
  created() {
    console.log(this.$attrs); // { "boo": "Html", "coo": "CSS", "doo": "Vue", "title": "前端工匠" }
  }
};
</script>

childCom2.vue

<template>
  <div class="border">
    <p>boo: {{ boo }}</p>
    <p>childCom2: {{ $attrs }}</p>
    <child-com3 v-bind="$attrs"></child-com3>
  </div>
</template>
<script>
const childCom3 = () => import("./childCom3.vue");
export default {
  components: {
    childCom3
  },
  inheritAttrs: false,
  props: {
    boo: String
  },
  created() {
    console.log(this.$attrs); // { "coo": "CSS", "doo": "Vue", "title": "前端工匠" }
  }
};
</script>

childCom3.vue

<template>
  <div class="border">
    <p>childCom3: {{ $attrs }}</p>
  </div>
</template>
<script>
export default {
  props: {
    coo: String,
    title: String
  }
};
</script>

$attrs表示没有继承数据的对象,格式为{属性名:属性值}。Vue2.4提供了$attrs , $listeners 来传递数据与事件,跨级组件之间的通讯变得更简单。

简单来说:$attrs$listeners 是两个对象,$attrs 里存放的是父组件中绑定的非 Props 属性,$listeners里存放的是父组件中绑定的非原生事件。

Vue.observable

mixin

mixin (混入) (谨慎使用全局混入, 如有必要可以设计插件并引入使用)参见官方文档

  • 一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项

  • 当组件和混入对象含有同名选项时,这些选项将以恰当的方式进行“合并”。数据对象在内部会进行递归合并,并在发生冲突时以组件数据优先。

  • 同名钩子函数将合并为一个数组,因此都将被调用。另外,混入对象的钩子将在组件自身钩子之前调用。

  • 值为对象的选项,例如 methods、components 和 directives,将被合并为同一个对象。两个对象键名冲突时,取组件对象的键值对。

路由传值 /引用数据类型值传递实现父子间数据的共享

总结

Common usage scenarios can be divided into three categories:

Father-child communication: The parent passes data to the child through props, and the child passes to the father through events ($emit); communication can also be done through the parent chain/child chain ($parent / $children );ref Also has access to component instances;provide/inject API;$attrs/$listenersBrother communication:Bus;VuexCross-level communication: Bus;Vuex;provide/inject API$attrs/$listeners

(Learning video sharing: vuejs introductory tutorial Programming basics video)

The above is the detailed content of [Summary] 11 communication methods of Vue components. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete