useVModel
v-model 绑定的简写,props + emit -> ref
先看v-model的写法
defineProps({
isShow: {
type: Boolean,
required: true
}
})
const emits = defineEmits(['update:isShow'])
function close() {
emits('update:isShow', false)
}
useVModel的写法
父组件
import { ref } from 'vue'
import addAd from './add_ad.vue'
const isShow = ref(true)
<addAd v-model:isShow="isShow" />
子组件
const props = defineProps({
isShow: {
type: Boolean,
required: true
}
})
const emit = defineEmits(['update:isShow'])
const eisShow = useVModel(props, 'isShow', emit)
function close() {
eisShow.value = false
}
<div @click="close">{{eisShow}}</div>
结果显示eisShow是true,点击后变false。此时父组件的isShow由原来的true变成false
当父组件没定义props里的isShow值,子组件可以用withDefaults给默认值
子组件
interface Props {
isShow: boolean
}
const props = withDefaults(defineProps<Props>(), {
isShow: true
})
const emit = defineEmits(['update:isShow'])
const eisShow = useVModel(props, 'isShow', emit)
function close() {
eisShow.value = false
}
<div @click="close">{{eisShow}}</div>
结果显示eisShow是true,点击后变false
此时父组件的isShow由原来的undefined变成false
如果有多个props值,并多处调用,那用useVmodel才有意义












网友评论