1. propsand$emitThe parent component passes data to the child component throughpropThe child component passes data to the parent by$emitTrigger events to do this
  2. .syncv-model(parent-child component data synchronization)
  3. $parent.$childrenMultilevel data transfer, intelligent component encapsulation
  4. $attrs(collection of attributes) and$listeners(Collection of methods). Vue 2.4 is now available$attrsand$listenersTo solve A->B->C problem, components pass down, can not usepropsRegistration.v-bindAttribute passing,v-onMethod is passed
  5. The parent component passesproviderTo provide variables that are passed in child componentsinjectTo inject variables.
  6. $refsFor instance
  7. envetBusA central event bus can be used for horizontal component data transfer

Props pass data

The parent component

<template> <div> Parent component: {{money}} <son1 :money='money' @addMoney = 'addMoney'></son1>
    </div>
</template>
<script>
import son1 from './son1'
export default {
    components:{
        son1
    },
    data() {return {
            money:100
        }
    },
    methods:{
        addMoney(val){
            this.money = val
        }
    }
}
</script>
Copy the code

Subcomponents son1. Vue

<template> <div> son 1 gets {{money}} < button@click ="raiseMoney"</button> </div> </template> <script>export default {
    props:{
        money:{
            type:Number,
            default:1
        }  
    },
    methods:{
        raiseMoney(){
            this.$emit('addMoney',200)
        }
    }
}
</script>
Copy the code

. Use of sync and V-Model (parent-child component data synchronization)

.sync

  • Requirements require “bidirectional binding” of a prop. Unfortunately, true bidirectional binding creates maintenance problems, because child components can modify the parent, and there is no obvious source of change in either parent or child.
  • In order toupdate:myPropNameMode triggers events instead
  • namely<son1 :money.sync='money'></son1>

    Subcomponents enclosing $emit (' update: money, 200)

    Is shorthand for the following code (syntactic sugar)

    @update:money="(val)=>this. Money => val"></son1>

    Subcomponents enclosing $emit (' update: money, 200)

v-model

  • <son1 :value="money" @input="(val)=>this.money=val></son1>
  • Or you could write it as<son1 v-model="money"></son1>
  • V-model is a method that child components can only receivevalue, has limitations, while.syncYou can name it whatever you want

Multiple levels of data transfer$parent $children

  • The grandchild component changes the parent component directly<button @click="$parent.$emit('addMoney',400)"> </button>

    If you have multiple grandchild components like this, it will always$parentGet down there. This is going to be a hassle. Why don’t we just package one$dispatch

    $dispatchOnly to inform himself of his father, andeventBusIt’s a global alert, to all fathers and sons
  • Package in main.vuedispatch

Up to inform

Vue.prototype.$dispatch = function (eventName,value){
    let parent = this.$parent;
    while(parent){
        parent.$emit(eventName,value);
        parent = parent.$parent}} only this is required.$dispatch('addMoney',400) //666 test is correctCopy the code

Pass down

  • It’s wrapped in main.js$broadcast
Vue.prototype.$broadcast = function(eventName,value){// Get all the children under the current component const broadcast = (children) => {children. ForEach (child => {child.$emit(eventName,value);
            if(child.$children){
                broadcast(child.$children)
            }
        })
    }
    broadcast(this.$children} only need to be used in the parent this.$broadcast('say',1111) Anything with say in son1.vue <Grandson :money = money@say ='say1'></Grandson>

    methods:{
        say1(val){
            console.log("I'm handsome."+val) } } <! -- Test console prints I am handsome -->Copy the code

$attrsCollection of attributes

  • $attrsProps () -props () -props () -props () -props () -props () -props () -props () -props$attrsI can pass the parent all at once when all the values are received, perfect
  • Use directly$attrsAfter receiving the data, open the console, and you’ll find that the properties are all mounted in the DOM, which we don’t want to be

    Solution: in use$attrsOn the child component of theinheritAttrs:false, the code is as follows

<! -- parent component --> <son2 name="Run" address="Beijing"></son2> <! Template > <div> <! --$attrsRepresents all attributes passed from the superior --> Son 2: {{$attrs}}
    </div>
</template>
<script>
export default {
    inheritAttrs:false} </script> <! Son 2: {"name": "Run"."address": "Beijing"} -- >Copy the code
  • How can the child component pass the retrieved data to the child component once again? Just do this:

    <grandson2 v-bind="$attrs"></grandson2>

    The same is used when the grandchild component is received$attrsYou can get all the data

$listenersCollection of methods

  • Methods that the parent binds to the child can be used in the child$listenersTo call these methods
  • If the child component does not use these methods, the grandchild component doesv-on="$listeners"To pass these methods to the grandchild component, which is used by the grandchild component$listeners
<! -- parent component --> <son2 name="Run" address="Beijing" @look="console.log('look')"></son2> <! -- subcomponent --> <grandson2 V-bind ="$attrs" v-on="$listeners"></grandson2>

<!--孙子组件-->
<template>
    <div>
        孙子2:{{$attrs}}
        <button @click="$listeners.look()"</button> </div> </template> <! -- Click the button on the grandchild component'look at'Is printed on the console'look'-->
Copy the code

provideProvide variables,injectRegistry variable

  • Problem: The address of the navigation bar changes but the page is not refreshed (the page is not refreshed with vue-router routing to the current page), such as the following search function

  • 1.this.$router.go(0);
  • 2,location.reload();

    The above two methods will have the problem of flash screen, and the user experience is not good

    How do products agree that I preferwindow.openthe
  • In app. vue, declare the reload method to control the display or hiding of the router-view, thus controlling the reloading of the page. (provide /inject )

The ancestor component provides a dependency to all its descendants.

  • App.vue 1. Declare variables in data 2. Bind V-if 3. 4. Inject dependencies into descendants



Inject accepts the method passed by app

$refsFor instance

  • refIs used to register reference information for an element or child component. Reference information will be registered in the parent component’s$refsOn the object.

    If used on a normal Dom element, the reference refers to the Dom element.

    If used on a child component, the reference points to the component instance, and the parent can use the method on the child component to pass$refs;
  • $refsThe relativedocument.getElementById, will reduce the consumption of dom node acquisition.
  • $refsIt is filled only after the component is rendered, and it is non-responsive. It is simply a contingency plan for working directly with child components – and should be avoided in templates or computed properties$refs
<! -- parent --> <son2 name="Run" address="Beijing" ref="son2"></son2>

    mounted(){
        this.$refs.son2.sleep() }, <! Son2 subcomponent --> methods:{sleep(){
            console.log('I want to sleep')}}Copy the code

Communicate eventBus across components

  • eventBusIt’s defined globally. Pass$on(eventName,function)Registered event, passed$emit (eventName, parameters)Get use event
<! -- Register bus--> vue.prototype on mian.js.$bus= new Vue(); <! Register the event on the appropriate page --> this.$bus.$on('I got a call.'.function(val){
        console.log('呵呵'+val) }) <! Use the event on the appropriate page --> this.$nextTick(()=>{
        this.$bus.$emit('I got a call.'.'xxx')}) <! -- Console print --> ha ha XXXCopy the code
  • New Premise().then(()=>{// wait until all code is synchronized})