绑定单个 v-model 用法
父组件:
<script setup lang="ts">
import { ref } from "vue";
import HomeView from "./views/HomeView.vue";
let str1=ref('你好')
</script>
<template>
<div>父组件:{{ str1 }}</div>
<HomeView v-model="str1"></HomeView>
</template>
子组件:
<script setup lang="ts">
defineProps<{
modelValue:string
}>()
const emit=defineEmits(['update:modelValue'])
const func=()=>{
emit('update:modelValue','我改变了父组件穿过来的值')
}
</script>
<template>
<button @click="func">按钮</button>
<div>子组件:{{ modelValue }}</div>
</template>
绑定多个 v-model 用法
父组件:
<script setup lang="ts">
import { ref } from "vue";
import HomeView from "./views/HomeView.vue";
let str1=ref('你好')
let str2=ref('测试')
</script>
<template>
<div>父组件-str1:{{ str1 }}</div>
<div>父组件-str2:{{ str2 }}</div>
<HomeView v-model="str1" v-model:inputVal="str2"></HomeView>
</template>
子组件:
<script setup lang="ts">
defineProps<{
modelValue:string
inputVal:string
}>()
const emit=defineEmits(['update:modelValue','update:inputVal'])
const func=()=>{
emit('update:modelValue','我改变了父组件穿过来的值')
}
const valText=ref<string>('sdfsdf')
const inputFunc=(e:Event)=>{
const elementInput=e.target as HTMLInputElement
emit('update:inputVal',elementInput.value)
}
</script>
<template>
<button @click="func">按钮</button>
<div>子组件:{{ modelValue }}</div>
<input @input="inputFunc" type="text" v-model="valText" />
<div>子组件:{{ inputVal }}</div>
</template>
绑定 v-model 并添加自定义修饰符用法
父组件:
<script setup lang="ts">
import { ref } from "vue";
import HomeView from "./views/HomeView.vue";
let str1=ref('你好')
let str2=ref('测试')
let str3=ref('早上好')
</script>
<template>
<div>父组件-str1:{{ str1 }}</div>
<div>父组件-str2:{{ str2 }}</div>
<div>父组件-str3:{{ str3 }}</div>
<HomeView v-model="str1" v-model:inputVal.myModifier="str2"></HomeView>
<HomeView v-model="str1" v-model:inputVal="str3"></HomeView>
</template>
子组件:
<script setup lang="ts">
const props=defineProps<{
modelValue:string
inputVal:string
inputValModifiers?:{ // 这里 ? 表示修饰符可选
myModifier:boolean
}
}>()
const emit=defineEmits(['update:modelValue','update:inputVal'])
const func=()=>{
emit('update:modelValue','我改变了父组件穿过来的值')
}
const valText=ref<string>('input初始值')
const inputFunc=(e:Event)=>{
const elementInput=e.target as HTMLInputElement
emit('update:inputVal',props?.inputValModifiers?.myModifier?elementInput.value+'添加了修饰符':elementInput.value)
}
</script>
<template>
<button @click="func">按钮</button>
<div>子组件:{{ modelValue }}</div>
<input @input="inputFunc" type="text" v-model="valText" />
<div>子组件:{{ inputVal }}</div>
</template>
注:在 Vue3 中 v-model 是破坏性更新的,v-model 其实是一个语法糖,通过 props 和 emit 组合而成