1.vueThe rules

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

2. A scene

2.1 Scenario Description

  • The parent component has $10,000
  • The child component references $10000 of the parent component
  • The child component costs $10 each time it clicks a button
  • The balance displayed by the child and parent components changes in the same way

2.2 Do not use the. Sync modifier

/ / the parent component
<template>
    <div class="app">App.vue I now have {{total}}<hr>
        <!-- 这里的 update:money 是一个字符串 -->
        <! Update :money event -->
        <! -- Use $evet to receive arguments passed by child components -->
        <Child :money="total" v-on:update:money="total = $event"/>
    </div>
</template>

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

<style>
.app {
    border: 3px solid red;
    padding: 10px;
}
</style>
Copy the code
/ / child component
<template>
    <div class="child">
        {{money}}
        <! $emit emit update:money event on parent component -->
        <! The first argument is the event name, and the second argument is the result of the argument.
        <button @click="$emit('update:money', money-10)">
            <span>To spend money</span>
        </button>
    </div>
</template>

<script>
    export default {
// Accept the money property from the parent component
// The child component cannot be modified directly, so it needs to be modified via $emit
        props: ["money"]};</script>

<style>
    .child {
        border: 3px solid green;
    }
</style>
Copy the code

Click 3 times, the result is shown below

2.3 Use the. Sync modifier

// The parent component is as follows, the child component remains unchanged
<template>
    <div class="app">App.vue I now have {{total}}<hr>
        <! -- Simplified code writing
        <Child :money.sync="total"/>
    </div>
</template>

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

<style>
    .app {
        border: 3px solid red;
        padding: 10px;
    }
</style>
Copy the code

3..syncThe role of

  • if the. Sync modifier is not used, the parent component will write
    ;

  • Sync =”total”/>

  • It is common for a child component to modify the properties of props, but the child component cannot modify the properties directly and must notify the parent component after the modification.

  • So the.sync modifier is necessary