current position:Home>Used in Vue projects Sync modifier and $emit (update: XXX)

Used in Vue projects Sync modifier and $emit (update: XXX)

2022-04-29 15:13:05Elephants and ants

Vue Project use .sync Embellishments and $emit(update:xxx)

Our common communication between parent and child components , Generally, it is the custom attribute of the parent component , Subcomponents through subcomponents props receive ,
If you want to modify the variables passed by the parent component , In general use this.$emit( Event name , Parameters ,…) Event submission in the form of
.sync yes vue Used to implement simple “ Two way binding ” The grammar sugar of .

.sync The function of the modifier

vue Of prop It is a one-way downlink binding : The father prop The update flows down to the child component , But not vice versa
But in some cases , We need to be right about prop Conduct “ Two way binding ”.
This is the time , You can use it .sync To solve , utilize EventBus, When a subcomponent triggers an event ,, The parent component will respond to the event and update the data , It avoids the child component directly modifying the content passed by the parent component .

Not used .sync Before the modifier

Parent component :

<parent :myMessage=“bar” @update:myMessage=“func”>

js Defined function :

func(val){
    
	this.bar = val;
}

Child components , Event trigger function :

func2(){
    
	this.$emit(‘update:myMessage’,valc);
}

  • in other words , The parent component needs to pass a binding value (myMessage)
  • At the same time, you need to set an update trigger function (func) Call when modifying the binding value of a sub component .

Use .sync Modifier writing

It will simplify the above writing , The parent component does not need to define the update trigger function .

Parent component :

<comp :myMessage.sync="bar"></comp>

Child components :

this.$emit('update:myMessage',valc);

  • If the event is not triggered this.$emit(‘update:show’, false); Then the external part cannot perceive the internal pair of subcomponents show Changes , Still think the value of this is true, Cause the pop-up box to open once , The back won't open again .

copyright notice
author[Elephants and ants],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204291513003264.html

Random recommended