Official documentation:
Form input components using custom events
The official also stated that v-model is just a syntactic sugar, and the real implementation depends on it
1. v- bind : Bind responsive data
2. Trigger input events and pass data (core and focus)
Basically:
Listen to the events of the native component, and when the value of the native component is obtained, the value is triggered by calling the $emit('input' ,data) method to trigger the input event
demo:
Parent component code:
<template> <div class="hello"> <button @click="ifShow=!ifShow">点击显示</button> <show-alert v-model="ifShow"></show-alert> </div> </template> <script> import showAlert from './showAlert.vue' export default { name: 'HelloWorld', components:{ showAlert, }, data () { return { ifShow:false, } } } </script>
Subcomponent code:
<template> <div id="showAlert" :value="value" v-if="ifValue"> <div>showAlert 内容</div> <button class="close" @click="ifValue=false">关闭</button> </div> </template> <script> export default{ props:{ value:{ type:Boolean, default:false, } }, data:function(){ return{ ifValue:false, } }, watch:{ value(bool){ this.ifValue=bool; console.log('bool='+ bool); }, ifValue(val){ /* Components using v-model will automatically listen for input events, * And pass the value carried by this input event to the property bound by v-model, * In this way, the value inside the component is given to the parent component */ this .$emit( ' input ' ,val); // Pass the value to the parent component, let the parent component listen to this change } }, } </script> <style scoped> .close{ background:red; color:white; } </style>
Realize the effect:
After clicking the show button:
前提: this.$emit('input',data);
After clicking the child component close button:
If this.$emit('input',data);
After clicking the child component close button:
If the value is not passed to the parent component through $emit, the parent component cannot monitor the changes of the child component.