A, $emit

The child component can reference the parent component’s data via props, so when the child component wants to modify this data, it can use $emit to modify the parent component’s data on the child component.

$emit receives two arguments:

  • {string} eventName Triggers events on the current instance.
  • [...args]Additional parameters are passed to the listener callback.

The sample

Scenario: The father gives the son money and the son wants to spend it. The son can see the specific amount of money, but the son cannot spend the money directly. The son needs to trigger an event, the father listens to this event, and the father receives the parameters passed by the son through $event

  • Child components can be called$emitPassing the event name to fire an event:
 //child.vue
<template>
    <div class="child">Dad have {{money}}<button @click="$emit('update:money', money - 10)">I want to spend money</button>
    </div>
</template>
  
<script>
  export default {
    props: ["money"]}</script>
  
<style>
      .child{
          border:1px solid green;
      }
      
</style>
Copy the code
  • Used on a child component of the parent componentv-onListen for this custom event, pass$eventAccepts arguments passed by the child component
//parent.vue
<template>
  <div class="parent">
    <div>Dad now has {{total}} yuan<hr/>
      <Child :money="total" v-on:update:money="total = $event"/>// :money="total"; money="total";</div>
  </div>
</template>

<script>
import Child from "./child.vue"
export default {
  components: { Child },
  data() {
    return {
      total: 10000}}}</script>

<style>
    .parent{
        border:1px solid red;
    }
</style>
Copy the code

Second, the sync

.sync simplifies the above code and is used directly on the parent component

//parent.vue
<template>
  <div class="parent">
    <div>Dad now has {{total}} yuan<hr/>
      <Child :money.sync="total"/>
    </div>
  </div>
</template>
Copy the code

:money. Sync =”total” equivalent to :money=”total” V-on :update:money=”total = $event”

Third, summary

  • Components cannot be modifiedpropsExternal data of
  • $emitCan trigger events and pass parameters
  • $eventYou can get$emitThe parameters of the