defineModel的行为与文档不一致

先来看看文档对defineModel的描述和使用例

html 复制代码
<script setup>
const model = defineModel()

function update() {
  model.value++
}
</script>

<template>
  <div>Parent bound v-model is: {{ model }}</div>
  <button @click="update">Increment</button>
</template>
html 复制代码
<Child v-model="countModel" />

不过这里的简单例子中 v-model的类型是数字类型 对它的变更自然也只有直接赋值这一种方式

那么 如果v-model是对象呢?

html 复制代码
<script setup lang="ts">
const countObj = defineModel<{ count: number }>()
</script>
<template>
  <div class="m-4">
    {{ countObj.count }}
    <el-button
      @click="
        () => {
          countObj.count++
        }
      "
    >
      +1
    </el-button>
  </div>
</template>
html 复制代码
<script setup lang="ts">
import { ref } from 'vue'
import Child from './Child.vue'

const countObj = ref({
  count: 1,
})
</script>
<template>
  <Child v-model="countObj" />
</template>

可以正常使用 v-model的value也是很正常的ref

然而如果改一下写法

html 复制代码
  <Child
    :model-value="countObj"
    @update:model-value="
      (val) => {
        debugger
        countObj = val
      }
    "
  />

就会发现@update:model-value根本没调用 这一点和文档是不一致的

如果countObj自身还是shallowRef(虽然一般也不会用) 那defineModel就会完全出错

这里的v-model甚至是一个完全没有响应性的变量 对它的变更不会触发渲染 也不会调用update事件

而如果使用之前的写法model-value + @update 就可以正常使用

html 复制代码
<script setup lang="ts">
const props = defineProps<{ modelValue: { count: number } }>()
const emit = defineEmits<{
  'update:modelValue': [val: { count: number }]
}>()
</script>
<template>
  <div class="m-4">
    {{ modelValue.count }}
    <el-button
      @click="
        () => {
          emit('update:modelValue', { count: modelValue.count + 1 })
        }
      "
    >
      +1
    </el-button>
  </div>
</template>

总结:1.defineModel的行为与文档不一致 2.shallowRef+defineModel会导致完全失效

相关推荐
ruanno_top3 小时前
点全选,已选的被清空了:Transfer 三态复选框的三个 bug
vue.js
时间的情敌4 小时前
Cesium 加载 3D Tiles 倾斜摄影、压平、样式设置(Vue3 实战)
vue.js·3d·cesium
usdoc文档预览21 小时前
USDOC系列之PPT文件在线编辑-VUE前端实现在线浏览器在线编辑PPT文档
前端·vue.js·编辑器·office365·ppt在线编辑·office文件在线编辑·文件在线编辑
Java小卷21 小时前
面向 schema 编程,轻松搞定 Element 虚拟化表格复杂应用场景
vue.js·低代码·element
仨孩子的爹1 天前
Lodop、hiprint 与 vue-print-designer:打印控件选型对比
vue.js
ruanno_top1 天前
四个 canvas 组件,在 2 倍屏上一直是糊的
vue.js
ruanno_top1 天前
一个脏数据能让整条折线消失:图表组件的四种数据契约
vue.js
FlyWIHTSKY2 天前
vue2和vue3有什么区别,用法上有哪些区别
前端·javascript·vue.js
ruanno_top2 天前
能点,但 Tab 不到:两个组件把「可操作」做了一半
vue.js
爱吃烧烤的技术渣2 天前
别再手写 CRUD 了:我把 Element Plus 的工作量压缩成一份列 schema
前端·vue.js