1、v-model特性
- 可以在原生元素上使用以实现数据的双向绑定
- 在组件上使用v-model会等价展开以下
:modelValue="text"
@update:modelValue="newValue=>text=newValue"
// 表明可以拿到修改的新值modelValue,改不改text的值是可选项 - 组件内部接收的话需要
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
- 可以通过v-bind="$attrs"透传,直到有人props接住
2、示例
1、父与子之间传递
- 父组件
- 给 VModelChild绑定message,采用等价展开的方式,并对传回来的新值进行修改再赋值
- 子组件
- 通过props接收modelValue,想要修改,但是不能直接修改props中的值,通过computed计算属性,发射修改的值,交给上层
<!-- 父组件 -->
<script setup>
import VModelChild from './VModelChild.vue';
import VModelmid from './VModelmid.vue';
import { ref, } from 'vue'
const message = ref('')
</script>
<template>
<h3>VModelParent</h3>
<div>信息为 : {{ message }}</div>
<VModelChild
:modelValue="message"
@update:modelValue="newValue => message = newValue+' ok ok '" />
</template>
<!-- 子 -->
<script setup>
import {computed} from 'vue'
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
const updateValue = computed({
get:()=>props.modelValue,
set:value=>emit('update:modelValue',value)
})
function editValue (){
updateValue.value = 'hello World'
}
</script>
<template>
<h3>VModelChild</h3>
<input type="text" :placeholder="modelValue">
<button @click="editValue">发送信息</button>
</template>
2、隔代传递
将父组件中绑定v-model的组件换为VModelMid
- 中间组件通过v-bind="$attrs"将v-model传递给VModelChild组件
- 并监听update:modelValue事件,接收传的值并展示
- 而Child中展示的信息为修改后的是由于读取的modelValue
<!-- 中间组件 -->
<script setup>
import VModelChild from './VModelChild.vue';
import { ref } from 'vue'
const message = ref('')
</script>
<template>
<h3>VModelmid</h3>
<p>信息为:{{ message }}</p>
<div>
<VModelChild @update:model-value="newValue=>message=newValue" v-bind="$attrs" />
</div>
</template>