Vue 3.x components realize two-way binding

1. The child component gets props and throws update:text event

<template>
    <div>
        <van-cell-group>
            <van-field v-model="text" label="文本" />
        </van-cell-group>
    </div>
</template>
<script>
import {
    
     ref, watch } from 'vue'
export default {
    
    
    name:"zzjInput",
    props:{
    
    
        text:{
    
    
            type:String,
            default:""
        }
    },
    setup(props,context){
    
    
        let text=ref('')
        watch(()=>props.text,(val)=>{
    
    
            text.value=val
        })
        watch(()=>text.value,(val)=>{
    
    
            context.emit('update:text',val)
        })
        return {
    
    
            text
        }
    }
}
</script>

2. Two-way binding of the parent component is actually one-way binding text and monitoring update:text events

<template>
    <div>
        <zzjInput v-model:text="val"></zzjInput>
    </div>
</template>
<script>
import zzjInput from '@/components/zzjInput'
import {
    
     ref, watch } from 'vue'
export default {
    
    
    components:{
    
    
        zzjInput
    },
    setup(){
    
    
        let val=ref('')
        watch(()=>val.value,(val)=>{
    
    //监听val,输入框变化,val变化则是实现了双向绑定
            console.log(val)
        })
        return{
    
    
            val
        }
    }
}
</script>

Note: In vue3, v-modal is not necessarily passed by value, but can be passed by any custom props, and the thrown event is update:xxx fixed as the form

Guess you like

Origin blog.csdn.net/weixin_44494811/article/details/113060440