Article directory
The concept of communication between components
Before we start, let's split the term communication between components
- components
- communication
We all know that components are one of the most powerful functions of vue, and we can regard every .vue
file in vue as a component. Communication means that the sender transmits information to the recipient in a certain format through a certain medium to achieve a certain purpose. In a broad sense, the communication of any information is the communication between communication components, which means that components ( .vue
) transmit information in a certain way to achieve a certain purpose. For example, we are using the table component in the UI framework, and some data may be passed into the table component, which essentially forms the communication between components.
What does inter-component communication solve?
In ancient times, people transmitted information through post stations, flying pigeons to send letters, beacon alarms, symbols, language, eyes, touch, etc. Today, with the rapid development of science and technology, communication is basically completed by wire or radio. Various communication methods such as wired telephones, landline telephones, wireless telephones, mobile phones, the Internet and even video telephones have appeared. From the above passage, we can see that the essence of communication is information synchronization, shared back to Vue, and between each component Each has its own scope, and the data between components cannot be shared. However, in actual development work, we often need to share data between components. This is also the purpose of component communication. To allow them to communicate with each other, in order to form An organic complete system.
Classification of communication between components
The classification of communication between components can be divided into the following
- Communication between parent and child components
- Communication between sibling components
- Communication between grandparent and descendant components
- Communication Between Non-Relational Components
relation chart:
The scheme of communication between components
Organize 8 conventional communication schemes in vue
- passing through props
- Trigger custom events through $emit
- use ref
- EventBus
$parent
or$root
- attrs and listeners
- Provide and Inject
- Vuex
props pass data
- Applicable scenario: parent component passes data to child component
- The subcomponent sets the props attribute to define the parameters passed by the parent component
- The parent component passes the value through the literal value in the use of the child component tag
eg:
childen.vue
components
props:{
// 字符串形式
name:String // 接收的类型参数
// 对象形式
age:{
type:Number, // 接收的类型为数值
defaule:18, // 默认值为18
require:true // age属性必须传递
}
}
Father.vue
components
<Children name="jack" age=18 />
$emit fires a custom event
- Applicable scenario: child components pass data to parent components
- The subcomponent
$emit
triggers a custom event, and$emit
the second parameter is the passed value - The parent component binds the listener to get the parameters passed by the child component
childen.vue
components
this.$emit('add', good)
Father.vue
components
<Children @add="cartAdd($event)" />
ref
- The parent component sets ref when using the child component
- The parent component gets data by setting the child component ref
parent component
<Children ref="foo" />
this.$refs.foo // 获取子组件实例,通过子组件实例我们就能拿到对应的数据
EventBus
- Usage scenario: Sibling component passing value
- Create a central event bus EventBus
- The sibling component
$emit
triggers a custom event, and$emit
the second parameter is the passed value - Another sibling component listens to custom events through $on
customizeBus.js
// 创建一个中央时间总线类
class Bus {
constructor() {
this.callbacks = {
}; // 存放事件的名字
}
$on(name, fn) {
this.callbacks[name] = this.callbacks[name] || [];
this.callbacks[name].push(fn);
}
$emit(name, args) {
if (this.callbacks[name]) {
this.callbacks[name].forEach((cb) => cb(args));
}
}
}
main.js
Vue.prototype.$bus = new Bus() // 将$bus挂载到vue实例的原型上
Or directly use the implemented bus in Vue
main.js
Vue.prototype.$bus = new Vue() // Vue已经实现了Bus的功能
Children1.vue
this.$bus.$emit('foo')
Children2.vue
this.$bus.$on('foo', this.handle)
$parent or $root
- Through the common ancestors
$parent
or$root
the establishment of correspondence associations
sibling component
this.$parent.on('add',this.add)
another sibling component
this.$parent.emit('add')
$attrs and $listeners
- Applicable scenario: ancestors pass data to descendants
- Set batch download attributes $attrs and $listeners
- Contains attribute bindings (except class and style ) that are not recognized (and picked up) as props in the parent scope.
- Internal components can be passed in via v-bind="$attrs"
// child:并未在props中声明foo
<p>{
{
$attrs.foo}}</p>
// parent
<HelloWorld foo="foo"/>
// 给Grandson隔代传值,communication/index.vue
<Child2 msg="lalala" @some-event="onSomeEvent"></Child2>
// Child2做展开
<Grandson v-bind="$attrs" v-on="$listeners"></Grandson>
// Grandson使⽤
<div @click="$emit('some-event', 'msg from grandson')">
{
{
msg}}
</div>
provide and inject
- Define the provide attribute in the ancestor component and return the passed value
- In the descendant component, receive the value passed by the component through inject
ancestor component
provide(){
return {
foo:'foo'
}
}
descendant component
inject:['foo'] // 获取到祖先组件传递过来的值
vuex
- Applicable scenarios: Component data transfer of complex relationships
- Vuex acts as a container for storing shared variables
- The place where state is used to store shared variables
- getter, you can add a getter derived state, (equivalent to the calculated property in the store), used to obtain the value of the shared variable
- Mutations are used to store methods for modifying state.
- Actions are also used to store and modify the state, but actions are performed on the basis of mutations. It is often used to do some asynchronous operations.
summary
- Component data transfer of parent-child relationship selects props and
$emit
for transfer, or ref - Component data transfer of sibling relationship is optional
$bus
, and secondly, you can choose$parent
to transfer - Ancestors and descendants component data transfer can choose attrs and listeners or Provide and Inject
- Component data transfer of complex relationships can store shared variables through vuex