Vue view updated data driven framework, vue for data communication between the components is very important.
Common usage scenarios can be divided into three categories:
-
-
Sons communication components: props / $ emit $ parent / $ children provide / inject ref $ attrs / $ listeners
-
Brothers components of communication: eventBus Vuex
-
Cross-level communication: eventBus Vuex provide / inject $ attrs / $ listeners
-
Parent components pass data to the subassembly by way of props, through $ EMIT subassembly may communicate to the parent component.
1. The value passed to the parent component subassembly (The props)
-
-
Pass a static value
-
<blog-post title="My journey with Vue"></blog-post>
-
-
Passed a dynamic value, any value type can be passed to a prop.
-
<blog-post v-bind:title="post.title"></blog-post> <blog-post v-bind:likes="42"></blog-post> <blog-post v-bind:is-published="false"></blog-post> <blog-post v-bind:comment-ids="[234, 266, 273]"></blog-post <blog-post v-bind:author="{ name: 'Veronica', company: 'Veridian Dynamics' }" ></blog-post>
Summary : props can only communicate, i.e., parent-child-way data flow component. And props is read-only and can not be modified, all changes will be warned.
2. The value transmitted to the parent sub-assembly component ($ EMIT)
$ Subassembly passes through the EMIT parameter to the parent components, the parent monitor parameters received and v-on.
Vue.component('welcome-button', { template: ` <button v-on:click="$emit('welcome')"> Click me to be welcomed </button> ` }) <div id="emit-example-simple"> <welcome-button v-on:welcome="sayHi"></welcome-button> </div> new Vue({ el: '#emit-example-simple', methods: { sayHi: function () { alert('Hi!') } } })
二、 $children / $parent
$ parent has access to the parent component instance current component, $ children have access to the current instance of the component sub-assemblies.
// parent components < Template > < div class = "the hello_world" > < div > {{MSG}} </ div > < COM-A > </ COM-A > < Button @click = "changeA" > Click change subassembly value </ Button > </ div > </ Template > < Script > Import from comA ' ./test/comA.vue ' export default { name: ' HelloWorld', components: { ComA }, data() { return { msg: 'Welcome' } }, methods: { changeA() { // 获取到子组件A this.$children[0].messageA = 'this is new value' } } } </script>
// subassembly < Template > < div class = "com_a" > < span > {} {} messageA </ span > < P > Get value of parent element: parentVal {{}} </ P > </ div > </ Template > < Script > Export default { Data () { return { messageA: ' the this Old IS ' } }, computed:{ parentVal(){return this.$parent.msg; } } } </script>
Note : $ parent and $ children do not get the same value, the value of $ children is an array, and $ parent is the object .
三、provide/ inject
provide / inject assembly is provided parent variables provide, in a subassembly and then injected variables inject.
provide a target or an object return function . inject an array or an object .
Note : This sub-assembly nested no matter how deep, as long as it can be called inject inject the data provide, without being limited to only get data from the current props property of the parent component.
// parent assembly provides a 'foo' var Provider = { Provide: { foo: 'bar' }, // ... } // subassembly injection 'foo' var Child = { Inject: [ 'foo' ], Created () { the console.log ( the this .foo) // => "bar" } // ... }
四、ref / refs
ref: DOM element in ordinary use, a reference point is the DOM element; used in the assembly, a reference point on a component instance , the component can be called directly by way of example a method or access data.
<Base-REF INPUT = "usernameInput"> <INPUT REF = "INPUT"> </ Base-INPUT> <Script> Methods: { // for focusing the input box assembly from the parent Focus: function () { the this $. refs.input.focus () } } </ Script>
Five, eventBus
eventBus bus also known as event, the same event is the center of all components in the common vue may register or send an event to the event reception center.
1. Initialization
We first need to create an event bus and export it to other modules or can be used to listen to it.
// event-bus.js import from view 'for' export EventBus const = new View ()
2. Send event
Suppose you have two components: additionNum and showNum, these two components can be brothers components can also be a father and components; here we brothers component as an example:
<template> <div> <show-num-com></show-num-com> <addition-num-com></addition-num-com> </div> </template> <script> import showNumCom from './showNum.vue' import additionNumCom from './additionNum.vue' export default { components: { showNumCom, additionNumCom } } </script>
- // addtionNum.vue transmitting event <template> <div> <button @ click = "additionHandle"> + adder </ button> </ div> </ template>
- <script> import {EventBus} from './event-bus.js' console.log(EventBus) export default { data(){ return{ num:1 } }, methods:{ additionHandle(){ EventBus.$emit('addition', { num:this.num++ }) } } } </script>
3. Receive event
// showNum.vue 中接收事件 <template> <div>计算和: {{count}}</div> </template> <script> import { EventBus } from './event-bus.js' export default { data() { return { count: 0 } }, mounted() { EventBus.$on('addition', param => { this.count = this.count + param.num; }) } } </script>
This realization of the sum of the component addtionNum.vue click the button, use the passed in showNum.vue the results show num sum.
4. Remove event listeners
If you want to remove the event listener, you can do this as follows:
import { eventBus } from 'event-bus.js'
EventBus.$off('addition', {})
Six, Vuex
Vuex is a specially developed for Vue.js application state management. It uses state of all components centralized storage management applications, the main problem is the development of large single-page project component communication problems.
If you want to know more about Vuex, I can see another blog: https://www.cnblogs.com/yaokai729/p/11447644.html
Seven, $ attrs and $ listeners
To address this demand, the introduction of the $ attrs and $ listeners, added inheritAttrs options. By default, not a parent scope prop identified (and obtain) binding characteristics (other than class style), will be "rolled back" and as regular HTML attributes applied on the root element subassembly. Next, look at an example of a cross-level communication:
// app.vue // index.vue <template> <div> <child-com1 :name="name" :age="age" :gender="gender" :height="height" title="程序员成长指北" ></child-com1> </div> </template> <script> const childCom1 = () => import("./childCom1.vue"); export default { components: { childCom1 }, data() { return { name: "zhang", age: "18", gender: "女", height: "158" }; } }; </script> // childCom1.vue <template class="border"> <div> <p>name: {{ name}}</p> <p>childCom1 of $ attrs: {{$ attrs}} </ P > < Child-COM2 V-the bind = "$ attrs" > </ Child-COM2 > </ div > </ Template > < Script > const childCom2 = () => Import ( " ./childCom2.vue " ); Export default { components: { childCom2 }, inheritAttrs: to false , // can not turn off automatically mounted in the attribute declaration props on the root element assembly props: { name: String // name作为props属性绑定 }, created() { console.log(this.$attrs); // { "age": "18", "gender": "女", "height": "158", "title": "程序员成长指北" } } }; </script> // childCom2.vue <template> <div class="border"> <p>age: {{ age}}</p> <p>childCom2: {{ $attrs }}</p> </div> </template> <script> export default { inheritAttrs: false, props: { age: String }, created() { console.log(this.$attrs); // { "gender": "女", "height": "158", "title": "程序员成长指北" } } }; </script>
八、localStorage / sessionStorage
Acquiring data window.localStorage.getItem (key), window.localStorage.setItem (key, value) data is stored.
to sum up:
-
props / $ emit is the most used, and most recommended way. Sons assembly suitable for communication.
-
Vuex Vue is a component of communication provided by the official, suitable for large-scale construction of single-page project.
-
$ Children / $ parent, ref, $ attr / $ listener main component to obtain data by operating the component Sons example, implement components communicate.