你声明我绑定
使用 defineModel() 声明一个双向绑定数据,使用变量接收。如 model,可以是任意合法标识符,并使用该数据
声明的是 ref 数据,所以逻辑中使用需要指定 model.value
子组件对数据的操作如 updata() 方法将影响到父组件绑定的数据
const model = defineModel() const update = () => model.value++
<div @click="update">{{ model }}</div>
使用 v-model 绑定某个数据,如 count,该数据和子组件的 model 建立起双向绑定
父组件对数据的操作,如自增方法也会影响到子组件的数据
import { ref } from 'vue'; import Model from './components/Child.vue'; let count = ref(0)
<div @click="count++">{{ count }}</div> <Model v-model ="count" />
const num = defineModel('num')
const num = defineModel('num', { type: Number, default: 0 })
<Model v-model:num ="count" />
const first = defineModel('first') const last = defineModel('last')
<input type="text" v-model="first"> <input type="text" v-model="last">
let user = ref({ first: 'gl', last: 'cn' })
<Model v-model:first="user.first" v-model:last="user.last" />
const props = defineProps(['dessert']) const dessertSelected = defineModel('dessertSelected', { default: [] })
<div class="reco-dessert"> <div class="item" v-for="(item, ind) in dessert" :key="item.id"> <input class="cb" type="checkbox" name="dessert" :id="item.id" :value="item.title" v-model="dessertSelected"> <label :for="item.id"> <img class="img" :src="`https://glpla.github.io/utils/${item.img}`" alt=""> <p>{{ item.title }}</p> <div class="price">¥{{ item.priceOrignal }}</div> </label> </div> </div>
import RecoDessert from '@/components/RecoDessert.vue'; const goods = ref({}) const goodsSelected = ref({ dessert: [] }) <RecoDessert :dessert="goods.dessert" v-model:dessertSelected="goodsSelected.dessert" />
const props = defineProps({ modelValue: Number }) const emit = defineEmits(['update:modelValue']) const incLike = () => { emit('update:modelValue', props.modelValue + 1) }
<div @click="incLike"><span class="fa fa-heart"></span> {{ modelValue }}</div>
let msg = ref(0)
<List v-model="msg"></List>
<List v-model:msg="msg" v-model:tips="tips"></List>
const props = defineProps(['msg', 'tips']) const emits = defineEmits(['update:msg', 'update:tips'])
<input type="text" :value="msg" @input="$emit('update:msg', $event.target.value)"> <input type="text" :value="tips" @input="$emit('update:tips', $event.target.value)">