• VueRule: This cannot be modified directly in a child componentpropsExternal data.
    • But we often make changes in child componentspropsTo implement this requirement, you can use JS’s publish and subscribe functionality (EventBus).
    • Look at a simple example: in child componentschildModify the parent componentfatherIn then The value of the
   // child.vue
   <tamplate>
       <div>
           {{compData}}
           <br />
           <button @click="$emit('update:compData', compdata + 1)">n + 1</button>
       </div>
   </tamplate>
   
   <script>
       export default {
           props: ["compData"]}</script>
Copy the code
    // father.vue
    <tamplate>
        <div>N: {{n}} of the parent component<br />
            <Child :compData.sync="n"/>
            <! <Child :compData="n" @update:compData="n = $event"/> 
        </div>
    </tamplate>
    <script>
        import Child from './child.vue'
        export default {
            data(){
                return {
                    n: 100}},components: {Child}
        }
    <script>
Copy the code
  • VueEncapsulates theEventBus
    • use$emitDefine and trigger events, and pass parameters; The event name should be:Update: specifies the name of the monitored data
    • use$eventTo get other components$emitThe parameters of the
  • Above, modifiers.syncIt is through$eventGet from other components$emitParameter is shorthand for the operation, which is a syntax sugar