Vue componentized communication provide & Inject, Dispatch,boardcast
February 1, 2024
by Michael O'Sullivan-Atkinson
No Comments
An introduction to
As the front end of the most easy to get started with the framework, Vue entry actually did not say what, I put a list of code, we can understand that can get started
<template>
<divid="app"><h1>{{title}}</h1><div><inputtype="text"v-model="val"><button @click="add">add</button><button @click="clear">empty</button></div><ul><liv-for="todo in todos":key="todo.title":class="{done:todo.done}"><inputtype="checkbox"v-model="todo.done">
{{todo.title}}
</li></ul><p>{{active}} / {{all}}</p></div></template>Copy the code
The content of Vuejs is as follows. After you are familiar with this example, it is our main text. If you don’t understand the above code, please go to the official website to review it
Variable rendering
Render loop
A class of rendering
Calculate attribute
The listener
The binding event
The life cycle
componentization
Vue single file component. The single file component of Vue is supported automatically through vue-CLI initials. create child1.vue
<template><divid="app"><Child1></Child1></div></template><script>import Child1 from'@/components/Child1'exportdefault {
name: "app".components:{Child1}
}
</script>Copy the codeCopy the code
The following ushered in the first common problem, if the component is much, how they communicate with each other, do not look down upon this problem, SAO gas of the interviewer, such as me, often like to ask, let’s demonstrate the Vue component between the commonly used communication to receive
1. Parent to child components
The simplest way to pass values to parent components is through props
// App
<template><divid="app"><Child1:title="title1"></Child1></div></template>Copy the code
Vue prefers one-way data flow, so the child component needs to notify the parent component to modify the passed data and use $emit to trigger the event passed by the parent element
div{
border:1px red solid;
padding:20px;
}
</style>Copy the code
// child1
<template><div><h2>Child2</h2><p>{{title}}</p><button @click="toParent">Passes to the parent element</button></div></template><script>exportdefault {
props: ['title'].methods:{
toParent(){
this.$emit('getmsg'.'Dad, I know I'm wrong.')}}
Copy the code
}
</script>Copy the code
3. Sibling components
Sibling components cannot communicate directly, just bridge the parent element and let everyone experience it
4. Provide and inject ancestors and descendants
Provice /inject API for functions, functions, functions, functions, functions, functions, functions, functions, functions, functions, functions
Many open source libraries now use this API to share data across hierarchies, such as the Tabs and select of Element-UI
<span class="hljs-attr">inject</span>:[<span class="hljs-string">'woniu'</span>]
Copy the code
Copy the code
} </script> Copy the code
However, provider and Inject are not responsive. If descendant elements want to notify ancestors, they need to hack. Vue1 has two methods, Dispatch and Boardcast, but vue2 is dead, we can simulate them ourselves
The principle is that you can pass this.Children to get the parent and the child, and we just recurse
5. dispatch
Getting $parent recursively is simple
<button @click="Dispatch ('dispatch',' Hello GrandGrandChild1')">dispatch</button>Copy the codeCopy the code
Notice that it only passes up, not affecting other elements
6. boardcast
Like Dispatch, $children is recursively acquired to broadcast to all child elements
<button @click="$boardcast (' boardcast ', 'I am Child1')">Broadcast child element</button>Copy the codeCopy the code
functionboardcast(eventName, data){
this.$children.forEach(child= > {
// The child element fires $emit
child.$emit(eventName, data)
if(child.$children.length){
// Recursive call to modify this to refer to the child via call
boardcast.call(child, eventName, data)
}
});
}
{
methods: {
$boardcast(eventName, data) {
boardcast.call(<span class="hljs-keyword">this</span>,eventName,data)
}
Copy the code
Copy the code
}}Copy the code
7. Mount Dispatch and Boardcast globally
If you want to use it, you need to use your own internal theorems dispatch and boardcast too tired, we mount it to the Vue prototype chain, isn’t it very high, find main.js
Vue.prototype.$dispatch = function(eventName, data) {
let parent = this.$parent
// Find the parent elementwhile (parent ) {
if (parent) {
// The parent element fires with $emit
parent.$emit(eventName,data)
// Find the parent element recursively
parent = parent.$parent
}else{
break}}}
Vue.prototype.children.forEach(child= > {
// The child element firesemit(eventName, data)
if(child.$children.length){
// Recursive call to modify this to refer to the child via call
boardcast.call(child, eventName, data)
}
});
}
Copy the code
Copy the code
So the components can be used directly without pressure
8. Irrelevant component: event-bus
If the two components have nothing to do with each other, we can only do this using subscription publishing mode and mount it on vue.protyType. Let’s try it. We call this mechanism bus mechanism, which is the much-loved event-bus
classBus{
constructor() {/ / {// eventName1:[fn1,fn2],// eventName2:[fn3,fn4],// }this.callbacks = {}
}
$on(name,fn){
this.callbacks[name] = this.callbacks[name] || []
this.callbacks[name].push(fn)
}
$emit(name,args){
if(this.callbacks[name]){
// The existence iterates through all the callbackthis.callbacks[name].forEach(cb= > cb(args))
}
}
}
Copy the code
Vue.prototype.$bus = new Bus()
Copy the code
use
/ / use
eventBus(){
this.$bus.$emit('event-bus'.'test eventBus')}/ / to monitorthis.$bus.$on("event-bus",msg=>{
this.msg = 'Receive event-bus message :'+ msg
})
Copy the codeCopy the code
In fact, Vue itself is a subscription publishing implementation, so we can delete the Bus class and create an empty Vue instance
Vue.prototype.$bus = new Vue()
Copy the codeCopy the code
9. vuex
fromVue Stubborn Bronze – Gateway and componentized communication G