一、v-model
1、v-model
可以在组件上使用以实现双向绑定。即父组件的值可以传递给子组件,子组件的值修改后,父组件的值会同步更新。
从 Vue 3.4 开始,推荐的实现方式是使用 defineModel() 宏;
2、示例:最常用的使用方式:父组件的值,传值给子组件,子组件的input绑定了此字段,这样子组件input的内容修改时,父组件里的值便会同步更新,示例如下
Vue SFC Playground
父组件
<script setup>
import Child from './Child.vue'
import { ref } from 'vue'
const msg = ref('Hello World!')
</script>
<template>
<h1>{{ msg }}</h1>
<Child v-model="msg" />
</template>
子组件
<script setup>
const model = defineModel()
</script>
<template>
<span>My input</span> <input v-model="model">
</template>
3、其他实例:父组件和子组件,弹窗的数据双向绑定
4、延伸:父组件想要传参给子组件多个双向绑定的数据,可以是用v-model的参数(v-model:title)
父组件
<script setup>
import { ref } from 'vue'
import MyComponent from './MyComponent.vue'
const bookTitle = ref('v-model argument example')
const content = ref('content')
</script>
<template>
<h1>{{ bookTitle }}</h1>
<h1>{{ content }}</h1>
<MyComponent v-model:title="bookTitle" v-model:content="content" />
</template>
子组件
<script setup>
const title = defineModel('title')
const content = defineModel('content')
</script>
<template>
<input type="text" v-model="title" />
<input type="text" v-model="content" />
</template>
二、props属性
props也是父组件的值传递给子组件,但是是单向数据流;子组件的值改变时,父组件的值不会同步更新,需要结合$emit('someEvent')来实现子组件的值同步更新到父组件;
我的理解是v-model的底层机制等同于props和$emit('someEvent')结合使用。