20190130 How do Vue components communicate?
- Start by figuring out the communication modes in the component
- Parent passes to child
- Child passes to parent
- Sibling transmission
- Mode of delivery
Props to pass
Code examples:
// parent
<template>
<child :content="content">
</template>
// child
props: {
content: String
}
$attrs, $listeners
Copy the code
The listeners attribute is like two libraries, one for props and one for events.
Code examples:
// parent
<template>
<child :content="content" :bar="bar" @one="one" @two="two" class="child" style="width:1rem">
</template>
// child
props: {
content: String,
one: Function
}
console.log(this.$attrs, this.$listeners)
// bar, two
$emit, $on
Copy the code
Code understanding:
$on('JS', function say(val) {// execute events and receive console.log('JS ', '+ daily question ')}) vm.$emit('JS',' daily question ') // trigger events on the current instanceCopy the code
Provide, Inject is mainly used by higher-order components and component libraries, which allows an ancestor component to inject dependencies for all its descendants
Code understanding:
// parent <template> <child /> </template> provide: {name: 'JS', value:' oF the day ',}, // child inject: {name: String, value: String} console.log(this.name, this.value) // JS, daily 题Copy the code
The EventBus idea is to declare a global Vue instance variable EventBus to store all communication data and event listeners
Global let EventBus = new Vue() // parent EventBus.$on('received', function (val) {console.log('received: '+ val) // child EventBus.$emit('received', 'JS ')Copy the code
Vuex
Vuex solves complex communication problems for large projects, which will not be covered here