Home>Article>Web Front-end> How to communicate between Vue components? Several ways of component communication
VueHow to communicate between components? The following article will introduce you to the communication method of Vue components. I hope it will be helpful to you!
#The two major features of vue are responsive programming and componentization. Component is the core function of Vue, but the scope of each component instance is independent of each other, which means that data between different components cannot directly reference each other. If you want to reference data across components, you need to use component communication. Before communicating, you must first understand the relationship between components:
As shown in the figure above:
Father-son relationship: A and B, A and C, B and D, C and E
Brother relationship: B and C
Intergenerational relationship (maybe more generations apart): A and D, A and E
Level relationship: B and E, D and E, etc.
props
/$emit
The parent component binds a custom property throughv-bind
, and the child component receives the data from the parent component throughprops
; the child component The component triggers the event through$emit
, and the parent component useson()
or usesv-on
on the custom tag of the child component to listen for events triggered by the child component. Customize events to receive data from subcomponents. (Learning video sharing:vue video tutorial)
The following uses an example to illustrate the parent component Pass the value to the child component. The parent component parent.vue passes the databooks:['JavaScript Advanced Programming', 'CSS New World', 'Illustrated HTTP Color Edition']
to the child component child.vue. And displayed in child.vue
// 父组件parent.vue
// 子组件child.vue
- {{item}}
Note: Passing data through props is one-way. When the parent component data changes, it will be passed to the child component, but the child component cannot modify the props. The passed data is used to modify the corresponding state of the parent component, which is the so-called one-way data flow.
Next, click the book list through the child component, trigger it with$emit()
, and then get it from the parent component
// 子组件child.vue
- {{item}}
// 父组件parent.vue
$parent
/$children
// 父组件parent.vue
// 子组件child.vue
- {{item}}
Note:$parent
gets the object, if there is no parent component at the top level What you get isundefined
; what you get in$children
is an array. If there are no sub-components on the bottom layer, you get an empty array; these two communication methods only Can be used for parent-child component communication
ref
#If ref is used on a normal Dom element, the reference points to the DOM element; if used on a child component, The reference points to the component instance, and the component's methods and data can be directly called through the instance
// 父组件parent.vue
// 子组件child.vue
provide
/inject
The ancestor component passes ##provideto provide variables, descendant components inject variables through
injectto obtain the data of ancestor components. No matter how deeply the descendant components are nested, as long as inject is called, the data in provide can be injected. . The following is the specific code:
// 父组件康熙
// 子组件雍正
// 孙组件乾隆
Note: provide/inject can only pass values from top to bottom, and is not responsive. If you want to become a responsive data provide, you need to provide a function
$emit/
$on
eventBus is also called event bus. In Vue, eventBus can be used as a communication bridge concept. It is like all components share the same event center and can register to send events or receive events to the center, so components can notify other components in parallel up and down.
$emit('name',args)
: name:发布的消息名称 , args:发布的消息$on('name',fn)
: name:订阅的消息名称, fn: 订阅的消息$once('name',fn)
: name:订阅的消息名称, fn: 订阅的消息。与$on相似但是只触发一次,一旦触发之后,监听器就会被移除$off('name',callback)
:name:事件名称,callback:回调监听器
eventbus可以实现任何组件之前的通信,下面以兄弟组件为例
// main.js // 全局添加事件总线 Vue.prototype.$bus = new Vue()
在parent.vue引入ChildA和ChildB组件,使它们成为兄弟组件
// 父组件parent.vue
在ChildA组件中用$emit
发送事件
// ChildA组件组件A
在ChildB组件中用$on
接收ChildA发送的事件
// ChildB组件组件B
注意:$on
监听的事件不会自动移除监听,因此在不用时最好使用$off
移除监听以免产生问题
$attrs
/$listeners
当组件为两级嵌套时,一般采用props
和$emit
,但遇到多级组件嵌套时这种方法就不太适用了,如果不做中间处理,只传递数据用How to communicate between Vue components? Several ways of component communication有点大材小用了。因此在vue2.4
中为了解决这一需求,便引入了$attrs
和$listeners
, 新增了inheritAttrs
属性
$attrs
:当父组件传递了很多数据给子组件时,子组件没有声明props来进行接收,么子组件中的attrs属性就包含了所有父组件传来的数据(除开已经props声明了的);子组件还可以使用v−bind="$attrs"
的形式将所有父组件传来的数据(除开已经props声明了的)传向下一级子组件,通常和interitAttrs
属性一起使用。$listeners
:包含了父组件中(不含.native
修饰器的)v-on 事件监听器,通过v-on="$listeners"
,可以将这些事件绑定给它自己的子组件
下面看一个例子:
// 父组件
// 子组件A组件A
{{ msgA }}
// 孙组件B组件B
{{ msgB }}
$attrs获取的结果:
$listeners获取的结果:
如代码和图所示组件A中props
声明接收了sex属性,因此组件中$attrs
获取的是父组件中绑定的除去sex属性的值;组件A中使用了v-bind="$attrs"
和v-on="$listeners"
,则组件B获取不仅是组件A中本身绑定的属性和方法还包含组件A获取父组件绑定的属性和方法
如果父组件传递了很多参数给子组件,而子组件没有用props完全接收,那么没有接收的这些属性作为普通的 HTMLattribute
应用在子组件的根元素上
如果你不希望子组件的根元素继承特性,你可以在组件的选项中设置inheritAttrs: false
以上面的组件B为例,当How to communicate between Vue components? Several ways of component communication(inheritAttrs默认为true)
当How to communicate between Vue components? Several ways of component communication
// 孙组件B export default { name: 'ChildB', inheritAttrs: false, data() { return { msgB: null } }, mounted() { this.msgB = this.$attrs console.log('组件B获取的$listeners:', this.$listeners) } }
Vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
状态管理包含以下几个部分:
视图发生变化会导致数据源的改变,数据源发生变化则会改变视图,则上面表示是一个“单向数据流”。但是当我们的应用遇到多个组件共享状态时,单向数据流的简洁性很容易被破坏:
因此,为了解决这种问题我们把组件的共享状态抽取出来,以一个全局单例模式管理。在这种模式下,我们的组件树构成了一个巨大的“视图”,不管在树的哪个位置,任何组件都能获取状态或者触发行为!
通过定义和隔离状态管理中的各种概念并通过强制规则维持视图和状态间的独立性,我们的代码将会变得更结构化且易维护。
1、state
:存储应用中需要共享的状态,是Vuex中的唯一数据源。
2、getters
:类似Vue中的计算属性computed
,getter的返回值会根据它的依赖被缓存起 来,且只有当它的依赖值发生了改变才会被重新计算。
3、mutations
:更改 Vuex 的 store 中的状态(state)的唯一方法,且mutation 必须是同步函数
4、actions
:类似于 mutation,提交的是 mutation,而不是直接变更状态;可以包含任意异步操作
5、modules
:将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割
// 父组件父组件
// 子组件A组件A
A获取的值: {{ count }}
// 子组件B组件B
B获取的值: {{ countB }}
store.js
import Vue from 'vue' import Vuex from 'How to communicate between Vue components? Several ways of component communication' Vue.use(Vuex) export default new Vuex.Store({ state: { count: 0, }, getters: { getCount: (state) => { return state.count } }, mutations: { countAdd(state, num) { state.count += num } }, actions: { countAdd(context, num) { context.commit('countAdd', num) } }, modules: { } })
localStorage
/sessionStorage
localStorage:本地存储对象,存储的数据是永久性数据,页面刷新,即使浏览器重启,除非主动删除不然存储的数据会一直存在
sessionStorage:与localStorage相似,但是只有在当前页面下有效,关闭页面或浏览器存储的数据将会清空
localStorage和sessionStorage常用的API:
setItem (key, value) —— 保存数据,以键值对的方式储存信息。 getItem (key) —— 获取数据,将键值传入,即可获取到对应的value值。 removeItem (key) —— 删除单个数据,根据键值移除对应的信息。 clear () —— 删除所有的数据 key (index) —— 获取某个索引的key
// 存储 setItem() { window.localStorage.setItem('name1', '小明') window.sessionStorage.setItem('name2', '小红') }
// 接收 receive() { const name1 = window.localStorage.getItem('name1') const name2 = window.sessionStorage.getItem('name2') console.log(name1) // 打印结果为:小明 console.log(name2) // 打印结果为:小红 }
localStorage和sessionStorage通过setItem()
存储数据会自动转换为String
类型,但是通过getItem()
其类型并不会转换回来(localStorage和sessionStorage使用方法一样,下面均以localStorage为例)
const num = 1 window.localStorage.setItem('num', num) const numRec = window.localStorage.getItem('num') console.log(numRec, typeof(numRec)) // 1 string
因此正确的存储方式应该为:存储之前用JSON.stringify()
方法将数据转换成json字符串
形式;需要使用数据的时候用JSON.parse()
方法将之前存储的字符串转换成json对象
const num = 1 window.localStorage.setItem('num', JSON.stringify(num)) const obj = { name: '小红', age: 18 } window.localStorage.setItem('obj', JSON.stringify(obj)) const numRec = JSON.parse(window.localStorage.getItem('num')) console.log(numRec, typeof(numRec)) // 1 'number' const objRec = JSON.parse(window.localStorage.getItem('obj')) console.log(objRec, typeof(objRec)) // {name: '小红', age: 18} 'object'
注意:localStorage.setItem()和sessionStorage.setItem()不能直接存储对象,必须使用JSON.stringify()
和JSON.parse()
转换实现
以上8种通信方式主要应用在以下三类场景:
props
/$emit
, and single parent-child component communication uses$parent>
/$children
is also more convenient; parent components often useref
to obtain child component instances; you can also useprovide
/inject
,$attrs
/$listeners
, andlocalStorage
/sessionStorage
eventBus
$emit
/$on
; complex data can useVuex
is more convenient; you can also uselocalStorage
/sessionStorage
;provide
/inject
and$attrs
/$listeners
; the data communicated across level components can be used if it is not complicatedeventBus
andlocalStorage
/sessionStorage
; if the data is complex, you can useVuex
, but be aware that the data stored in Vuex will disappear when you refresh the interfaceThis article simply records the commonly used component communication methods, and does not introduce its details in depth. If there are any mistakes, please correct me
( Learning video sharing:web front-end development,Basic programming video)
The above is the detailed content of How to communicate between Vue components? Several ways of component communication. For more information, please follow other related articles on the PHP Chinese website!