Application scenarios

In actual development, a scenario like this might occur:

  • There are parent components. Assume that the ParentComponent is named ParentComponent and the ChildComponent is named ChildComponent
  • There is data defined in the ParentComponent ParentComponent: ParentData
  • ParentData is used in the ChildComponent ChildComponent
  • Data in the parent component ParentData needs to be updated based on data usage in the child component

Problems in the scenario

Vue provides that components cannot modify external data of props. In the preceding scenario, a child component cannot modify Parentdata of the parent component directly.

The solution

  • Use this.$emit to emit the event and pass the parameter as follows:
<template>
    <div class="ChildComponent">
        {{ParentData}}
        </button @click="$emit("update:data)", fn(ParentData)>
        do fn() to the ParentData
        </button>
    </div>
</template>
<script>
export default {
    props: ["ParentData"]
}
Copy the code
  • Get event to get emit parameters in the parent component using the following code example:
<template>
    <div class="ParentComponent">
        父组件data为 {{ParentData}}
        <ChildComponent :data="Parentdata" v-on:update:data="Parentdata" = $event"/>
    </div>
</template>
<script>
import Child from "./ChildComponent.vue"
export default {
    data() {
        return { ParentData: something }
        },
        components: {ChildComponent: ChildComponent}
}
</script>
Copy the code

The sync syntactic sugar

Vue provides the. Sync modifier syntax sugar to encapsulate statements in ParentComponent that use ParentData in ChildComponent with:

<ChildComponent :data.sync="ParentData"/>
Copy the code

Instead of

<ChildComponent :data="Parentdata" v-on:update:data="Parentdata" = $event"/>
Copy the code

Vue Other modifiers

  • @click.stop = “XXX” to prevent events from bubbling
  • @click.prevent = “XXX” to prevent default events
  • @keypress.enter = “XXX”, when the [Enter] key is pressed to execute the corresponding content