v-model
vue3 的v-model是破坏性更新的
其实是通过props和emit组合而成的语法糖
默认值的改变
- prop: value -> modelValue
- 事件:input -> update:modelValue
- v-bind 的.sync 修饰符和组件的model选项已移除
- 新增 支持多个v-model
- 新增 支持自定修饰符 Modifiers
例子
父组件:使用v-model给子组件绑定modelVal数值,v-model:title绑定新值
<template>
<button @click="show = !show">开关{{show}}</button>
<Dialog v-model="show" v-model:title.isBt="title"></Dialog>
</template>
<script setup lang='ts'>
import Dialog from "./components/Dialog/index.vue";
import {ref} from 'vue'
const show = ref(false)
</script>
子组件: 使用defineProps接收父组件绑定值,
<template>
<div v-if='propData.modelValue ' class="dialog">
<div class="dialog-header">
<div>标题---{{title}}</div><div @click="close">x</div>
</div>
<div class="dialog-content">
内容
</div>
</div>
</template>
<script setup lang='ts'>
type Props = {
modelValue:boolean,
title: string,
titleModifiers?: {
isBt: boolean
}
}
const propData = defineProps<Props>()
const emit = defineEmits([
'update:modelValue',
'update:title'
])
const close = () => {
emit('update:modelValue',false)
if (propData?.titleModifiers?.isBt) {
// 如果title使用了isBt修饰符,就可以在这里对值做出一些修改
}
emit('update:title','我要改变')
}
</script>
自定义修饰符通过在defineProps定义变量名+Modifiers, 如titleModifiers 自带的修饰符有lazy,trim,number
