We all know that v-model is actually a syntactic sugar of vue, used to create two-way bindings on form controls or components.
//Use v-model on form control<template> <input type="text" v-model="name" /> <input type="checkbox" v-model="checked"/> <!--The aboveinputAnd the followinginputThe effect is the same--> <input type="text" :value="name" @input="name="/> <input type="checkBox" :checked="checked" @click=/> {{name}} </template> <script> export default{ data(){ return { name:"", checked:false, } } } </script>
Props communication between parent-child components in vue is one-way. The parent component passes the value down to the child component through props, and the child component triggers the method in the parent component through $emit. Therefore, custom components cannot directly use v-model to implement v-model bidirectional binding. So is there any way to achieve it?
// Parent component<template> <div> <c-input v-model=""></c-input> <c-input v-model=""></c-input> <!--The aboveinputEquivalent to the followinginput--> <!--<c-input :value="" @input="="/> <c-input :value="" @input="="/>--> </div> </template> <script> import cInput from "./components/Input" export default { components:{ cInput }, data() { return { form:{ name:"", password:"" }, } }, } </script>
//Subcomponent cInput<template> <input type="text" :value="inputValue" @input="handleInput"> </template> <script> export default { props:{ value:{ type:String, default:"", required:true, } }, data() { return { inputValue:, } }, methods:{ handleInput(e){ const value=; =value; this.$emit("input",value); }, } } </script>
According to the above example code, we can see that the child component c-input has bound the value of the parent component form, and receives this value through:value in the child component. Then we modify this value in the child component, and trigger the input event in the parent component through $emit and assign the modified value to the form again.
In summary, we realize two-way data binding in custom components!
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.