子组件:
<template>
<div>
<button @click="fn">改变值</button>
<div>{{thisValue}}</div>
<slot/>
</div>
</template>
<script setup lang="ts">
// 实现v-model ===> :modelValue + @update:modelValue
import { ref,watch } from 'vue'
const props = defineProps({
modelValue:{
type:String,
default:'这是默认的modelValue'
}
})
const thisValue = ref()
watch(()=>props.modelValue,()=>{
thisValue.value = props.modelValue
},{immediate:true})
const emit = defineEmits(['update:modelValue'])
const fn = () => {
thisValue.value = '子组件页面改变值'
emit('update:modelValue',thisValue)
}
</script>
父组件:
<template>
<div>user</div>
<Comps @click="change()" v-model="thisValue"><template #default>{{thisValue}}</template></Comps>
//等同于
<Comps @click="change()" :modelValue="thisValue" @update:modelValue="thisValue = $event"><template #default>{{thisValue}}</template></Comps>
</template>
<script setup lang="ts">
import Comps from './comps.vue'
import { ref, watch } from 'vue'
const inputVal = ref('')
watch(inputVal,(newVal:any,oldVal)=>{
inputVal.value = newVal
console.log(inputVal.value)
})
const thisValue = ref('这是父组件页面的thisValue')
const change = () => {
thisValue.value = '父组件页面改变值'
}
</script>