computed拦截v-model

一,问题

在父组件和子组件中都使用v-model会打破单项数据流。


二,方法

基于上述问题采用computed拦截v-model

复制代码
<!-- 父组件 -->
<template>
  <div>
    <my-component v-model="form"></my-component>
  </div>
</template>
<script setup>
import myComponent from "./components/MyComponent.vue";
import { ref } from "vue";

const form = ref({
  name:'coderkey',
  age:18,
  sex:'男'
})
</script>

<!-- 子组件 -->
<template>
  <div>
    <el-input v-model="form.name"></el-input>
    <el-input v-model="form.age"></el-input>
    <el-input v-model="form.sex"></el-input>
  </div>
</template>
<script setup>
import { computed } from "vue";

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },
});
// const emit = defineEmits(["update:modelValue"]);
const emit = defineEmits();

const form = computed({
  get() {
    return props.modelValue;
  },
  set(newValue) {
    console.log('属性改变了')
    emit("update:modelValue", newValue);
  },
});
</script>

三,注意

最后发现问题:form.xxx = xxx时,并不会触发computedset,只有form = xxx时,才会触发set

解决方法:用watch监听器或者用Proxy代理对象。


四,Proxy + computed拦截v-model的对象

复制代码
<!-- 父组件 -->
<template>
  <div>
    <my-component v-model="form"></my-component>
  </div>
</template>
<script setup>
import myComponent from "./components/MyComponent.vue";
import { ref } from "vue";

const form = ref({
  name: "coderkey",
  age: 18,
  sex: "男",
});
</script>

<!-- 子组件 -->
<template>
  <div>
    <el-input v-model="form.name"></el-input>
    <el-input v-model="form.age"></el-input>
    <el-input v-model="form.sex"></el-input>
  </div>
</template>
<script setup>
import { computed } from "vue";

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },
});

// const emit = defineEmits(["update:modelValue"]);
const emit = defineEmits();
const form = computed({
  get() {
    return new Proxy(props.modelValue, {
      get(target, key) {
        return Reflect.get(target, key);
      },
      set(target, key, value) {
        emit("update:modelValue", {
          ...target,
          [key]: value,
        });
        return true;
      },
    });
  }
});
</script>

相关推荐
晴殇i几秒前
最近在 Github 名字叫“马尾辫”,这个真的很有趣看到头像
前端·后端·开源
10mAh8 分钟前
【PaddleOCR】扫描版 PDF 无法复制、RAG 检索为空怎么解决?——OCR 解析与版面还原实战
前端·pdf·ocr
IMPYLH13 分钟前
HTML 的 <embed> 元素
前端·数据库·html
IT_陈寒20 分钟前
Vite打包时静态资源404?加个斜杠就能解决
前端·人工智能·后端
沐土Arvin28 分钟前
音频录制sdk开发
前端·微信
anyup28 分钟前
【2026年8月】uView Pro 千星,还拿到了 GVP
前端·uni-app·github
必须会一定会42 分钟前
用纯 HTML/JS 做一个 AI 需求澄清器:把模糊想法转换成可执行任务书
开发语言·前端·javascript·人工智能·html·ai编程
10mAh1 小时前
【Linux】error while loading shared libraries 怎么解决?——ldd、RPATH 与动态链接排错
java·linux·前端
深念Y1 小时前
stable-diffusion.cpp 的 FLUX.2 Klein 9B 分步
java·前端·数据库
小帅不太帅1 小时前
1.5M 参数的 OCR 模型,我把它跑进了浏览器
前端·javascript·ai编程