For example, there is input in the subcomponent. If you want to realize two-way binding of the properties and value values in the props of the subcomponent, you can add a data or computed property to the subcomponent to replace the properties in the props, and then realize the binding.
//如果不改变父组件的值
<div>
<cpn :cmessage="message">
</div>
<template>
<h2>{
{
cmessage}}</h2>
<input type="text" v-model="dmessage">
</template>
components:{
cpn:{
props:{
cmessage:String;
},
data(){
dmessage:this.cmessage
}
}
}
//如果想改变父组件的值
<div>
<cpn :cmessage="message" @meschange="mchange">
</div>
<template>
<h2>{
{
cmessage}}</h2>
<input type="text" :value="dmessage" @input="mesInput"> //结合双向绑定的本质
<input type="text" v-model="dmessage"> //然后组件里用watch监听dmessage,效果一样
</template>
components:{
cpn:{
template:``,
props:{
cmessage:String;
},
data(){
dmessage:this.cmessage
},
methods:{
mesInput(event){
this.dmessage=event.target.value;
this.$emit('meschange',this.dmessage)
}
}
}
}
const app = new Vue({
el:'#app',
data:{
message:''
},
methods:{
mchange(newvalue){
this.message = newvalue;
}
}
})