preface

Made the company system for half a year, finally on the day before yesterday. It took too long to change the bugs in the later stage, and most of the bugs appeared were caused by the asymmetry of information between the front end and the back end. There were few logical errors, and the user experience was a little poor. After all, it was the first time to build such a large system (100W +). In terms of how to better cooperate with back-end personnel in development and how to design to improve user experience, I did not pay attention to this aspect before when I was doing development by myself. I only paid attention to functional implementation, and I made many compensations in the later stage.

After the launch of the project, the following is the maintenance update in the later period. Recently, the time is not so busy as before, and I simply did a review of the system.





This chapter will be a summary of the 8 methods of Vue component communication, daily development component communication is close, Familiarity with component communication can lead to better business development.

VuePass values between components

1. The parent component passes values to the child component

    1. Introduce child components into parent components
    1. Registering a subcomponent
    1. Used in pages, dynamic bindings pass in dynamic/static values on child component labels
    1. In a child component, use propsTo accept theThe parent componentThe passed value

The value received by a child component can be of either a reference type or a normal type:

  • Common types: String, Number, Boolean, Null
  • Reference types: Array, Object
# Parent component <template> <div> <! --> <Test :obj="obj" info=" Test "/> </div> </template> <script> /components/Test.vue"; Export default {name: "about", // register subcomponent components: {Test,}, data() {return {obj: {code: 200, title: "Front-end self-learning community ",},}; }}; </script>
<template> <div> <h1>{{obj.code}}</h1><br> <h2>{{obj.title}}</h2> <h3>{{info}}</h3> </div> </template> <script> export Default {name:'test', props:{obj:Object, info: [String,Number]}} </script>

Due to the
VueIs a one-way data flow,
Child componentsYes cannot be modified directly
The parent componentThe value of the.

2. The child component passes values to the parent component

The child component passes the binding event
$emit(' emit function name ', pass parameter)

@modify="modifyFatherValue"/> <script> /components/Test.vue"; Export default {name: "about", // register child components: {Test,}, data() {return {MSG :' I am the parent '}; }, methods:{// Take the value passed by the child component and assign it to the property modifyFatherValue(e){this.msg = e}}}; </script>
</button> <script> export default {name:'test', Methods :{modifyValue(){this.$emit(' modifyValue ',' modifyValue ')}}} </script>

3. The parent component passes $refs / $children To get the child component value

$refs :

  • Gets DOM elements and component instances to get component properties and methods.
  • By binding on child components ref, the use ofThis.$refs.refname. subcomponent properties/subcomponent methods

$children :

  • A child component of the current instance, which returns a collection of child components. If you want to retrieve a component property or method, you can use theThis.$children[index]. $children[index]

Sample Text component

<script> export default {name:'test', data() {return {datas:" props:{obj:Object, info: [String,Number]}, methods:{getValue(){console.log(' I'm Test1')}}} </script>

Sample Text2 component

< span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 13px! Important; word-break: inherit! Important;" Data (){return {datas:" Test2"}}, created(){console.log(this.parent.obj) this.parent.getQuery()}, methods:{ getTest2(){ console.log(this.datas) } } } </script>

refs

<template> <div> </template> // bind the child component to ref <Test ref="son" /> <Test2/> </div> </template> // get the child component properties and methods console.log( this.$refs.son.datas) this.$refs.son.getValue()

$children

$children[0].getValue(); $children[0].getValue(); $children[1].gettest2 (); $children[1].gettest2 (); / / I'm Test2 console. The log (` -- -- -- -- -- -- -- -- - ${enclosing $children [1]. The datas} `); / / I'm Test2

4. The child component passes $parentTo get properties and methods of the parent component instance

<script>
    export default {
        name:'test',
        created(){
         console.log( this.$parent.obj ) 
         this.$parent.getQuery()
        },
        
    }
</script>

5. $attrs $listenersGet parent component instance properties and methods (for component nesting)

$attrs: Contains feature bindings (except class and style) that are not considered (and not expected) props in the parent scope, and can be passed in internal components via v-bind= “$attrs”. When a component does not declare any props, it contains all parent scope bindings (except class and style).

$Listeners: Contains v-ON event listeners in the parent scope (without the.native modifier) It can pass in internal components via V-on = “$Listeners”. It is an object that contains all event listeners that are applied to this component, as if the child component inherits events from its parent component.

Use scenario: Use in the case of multiple nested components, you can avoid using Vuex to do data processing, use v-bind="$attrs" v-on="$listeners"Very convenient to achieve business data transfer.

The parent component

<template> <div> <Test3 :status="status" :title="title" @getData="getData" /> </div> </template> <script> import Test3 from ".. /components/Test3.vue"; Export default {name:'person', data(){return {title:'personal component ', status: false } }, methods:{ getData(){ console.log(this.title) } }, components:{ Test3 } } </script>

The child component 1

<div> <h1>Test3 </h1> <br /><br /> <Test4 v-bind=" props "v-on=" props "/> </div> </ listeners > <script> // Import Test4 from ".. /components/Test4"; export default { name: "test3", props: ["title"], components: { Test4, }, created() { console.log(this.$attrs); //{status: false} console.log("-----------"); console.log(this.$listeners); // {getData: ƒ}},}; </script>

Nested child components

<template> <div> <h1>Test4 </h1> </div> </template> <script> export default {name:' Test4 ', created(){ console.log('-----Test4------') console.log(this.$attrs) //{status: False} console.log(this.$listeners) // {getData: ƒ}}} </script>

6. Pass values across components

Create a js file, import vue, export vue instance; The global component data can then be shared by binding the $EMIT event to the exported instance and then listening for the event triggered by the $on.

Usage scenario:

It can meet the requirements of any scenario to pass data, parent component pass value, child parent pass value, brother components pass value, cross-level components pass value.

This scheme can be used when the communication data is relatively simple, but can be used when the project is large Vuex .

vue .js

/*
 * @Description: 
 * @Author: ZhangXin
 * @Date: 2021-01-22 15:48:56
 * @LastEditTime: 2021-01-22 15:51:24
 * @LastEditors: ZhangXin
 */

 import Vue from 'vue'

 export default new Vue()

Component A

<! -- * @Description: * @Author: ZhangXin * @Date: 2021-01-22 14:44:17 * @LastEditTime: 2021-01-22 16:25:33 * @LastEditors: ZhangXin --> <template> <div> <button @click="changeValue"> </button> </div> </template> <script> import zxVue from '.. /util/newVue.js'; Export default {name:'person', data(){return {title:'personal component ', status: $emit("getTitle", this.title)}}} </script>

Component C

<! -- * @Description: * @Author: ZhangXin * @Date: 2021-01-22 15:07:30 * @LastEditTime: 2021-01-22 16:26:38 * @LastEditors: ZhangXin --> <template> <div> <h1>Test4 component </h1> <h1>{{title}}</h1> </div> </template> <script> import zxVue from ".. /util/newVue"; export default { name: "test4", data() { return { title: "test4", }; $on("getTitle", (item)) => {this.title = item; $on("getTitle", (item)) => {this.title = item; console.log(item) }); }}; </script>

7. Vuex

Here is not to introduce, finished to write a separate article elaborate
Vuex

8. provide injectImplement the parent component to pass values to its children and grandchildren. (No limit on level)

The provide and Inject options need to be used together to allow an ancestor component to inject a dependency into all of its descendants, regardless of how deep the component hierarchy is, for as long as the upstream and downstream relationships are established.

provide :

  • Is an object or a function that returns an object
  • This object contains properties that can be injected into its descendants.

inject :

  • Is either an array of strings or an object
  • Used to inject into a child or descendant component provideParent component properties provided.

Usage scenario:

Provide/Inject provides easy cross-level access to the parent component's data

Provide (){return {name:' test '}} #inject inject:['name']

The parent component

<! -- * @Description: * @Author: ZhangXin * @Date: 2021-01-22 23:24:16 * @LastEditTime: 2021-01-22 23:49:50 * @LastEditors: ZhangXin --> <template> <div> <h1> I am the parent component </h1> <Son /> </div> </template> <script> import Son from '.. /components/son/SonOne' export default { name:'father', provide(){ return { titleFather: }}, components:{Son}, data(){return{title:' I am the parent '}},} </script>

Child components

<template> <div> <h1> </h1> </div> </template> <script> import SonTwo from '.. /son/SonTwo' export default { name:'sonone', components:{ SonTwo }, inject:['titleFather'], Created () {the console. The log (` ${enclosing titleFather} -- -- -- -- -- -- -- -- -- -- -- SonTwo `)}, the data () {return {title: 'I am a child components'}},} < / script >

Sons of components

<template> <div> <h1> </h1> </div> </template> <script> import SonTwo from '.. /son/SonTwo' export default { name:'sonone', components:{ SonTwo }, inject:['titleFather'], Created () {the console. The log (` ${enclosing titleFather} -- -- -- -- -- -- -- -- -- -- -- SonTwo `)}, the data () {return {title: 'I am a child components'}},} < / script >

conclusion

❤️ follow + like + collect + comment + forward ❤️, original is not easy, encourage the author to create better articles