在Vue3中 v-model 是破坏性更新的
v-model在组件里面也是很重要的
v-model 其实是一个语法糖 通过props 和 emit组合而成的
案例:
点击父组件中的按钮开关,控制子组件显示框的显示与隐藏
父组件:
<template>
<h1>我是APP.vue父组件</h1>
<div>isShow:{{isShow}}</div>
<br>
<button @click="change">开关</button>
<hr>
<vModel v-model="isShow"></vModel>
</template>
<script setup lang='ts'>
import {ref} from 'vue'
// 引入子组件
import vModel from './components/v-model/v-model.vue'
const isShow = ref<boolean>(true)
// 按钮点击事件 使子组件的显示或隐藏
const change = ()=>{
isShow.value = !isShow.value
}
</script>
子组件
注意:prop:value
-> modelValue
;
通过defineProps 接收 v-model传递的值 ===== modelValue
// 点击子组件的关闭按钮,改变modelValue的值,通过defineEmits并将值传递给父组件
<template>
<div class="dialog" v-if="modelValue">
<button class="btn" @click="close">关闭</button>
{{ modelValue }}
<h2>我是v-model子组件 dialog</h2>
<div>内容:<input type="text" @input="input"></div>
</div>
</template>
<script setup lang='ts'>
defineProps<{
modelValue:boolean,
}>()
const emit = defineEmits(['update:modelValue'])
// 点击子组件的关闭按钮,改变modelValue的值,并将值传递给父组件
const close = ()=>{
emit('update:modelValue',false)
}
</script>
<style scoped lang="less">
.dialog{
position: relative;
width: 500px;
height: 150px;
border: 5px solid #999;
padding: 0 10px;
display: flex;
flex-direction:column;
.btn{
position: absolute;
top: 10px;
right: 10px;
}
}
</style>
绑定多个案例
父组件
<template>
<h1>我是APP.vue父组件</h1>
<div>isShow:{{isShow}}</div>
<div>text:{{ text }}</div>
<br>
<button @click="change">开关</button>
<hr>
<vModel v-model="isShow" v-model:textVal="text"></vModel>
</template>
<script setup lang='ts'>
import {provide, ref,readonly} from 'vue'
import vModel from './components/v-model/v-model.vue'
const isShow = ref<boolean>(true)
const change = ()=>{
isShow.value = !isShow.value
}
const text = ref<string>('春分')
</script>
<style scoped>
</style>
子组件
<template>
<div class="dialog" v-if="modelValue">
<button class="btn" @click="close">关闭</button>
{{ modelValue }}
<h2>我是v-model子组件 dialog</h2>
<div>内容:<input type="text" :value="textVal" @input="input"></div>
</div>
</template>
<script setup lang='ts'>
const props = defineProps<{
modelValue:boolean,
textVal:string,
}>()
const emit = defineEmits(['update:modelValue','update:textVal'])
const close = ()=>{
emit('update:modelValue',false)
}
const input = (e:Event)=>{
const target = e.target as HTMLInputElement
emit('update:textVal', target.value)
}
</script>