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>

相关推荐
returnfalse几秒前
🔥 解密StreamParser:让数据流解析变得如此优雅!
前端
凉城a1 分钟前
经常看到的IPv4、IPv6到底是什么?
前端·后端·tcp/ip
jserTang7 分钟前
Cursor Plan Mode:AI 终于知道先想后做了
前端·后端·cursor
木觞清12 分钟前
喜马拉雅音频链接逆向实战
开发语言·前端·javascript
一枚前端小能手15 分钟前
「周更第6期」实用JS库推荐:InversifyJS
前端·javascript
叉歪16 分钟前
纯前端函数,一个拖拽移动、调整大小、旋转、缩放的工具库
javascript
Hilaku17 分钟前
"事件委托"这个老古董,在现代React/Vue里还有用武之地吗?
前端·javascript·vue.js
前端缘梦22 分钟前
Webpack 5 核心升级指南:从配置优化到性能提升的完整实践
前端·面试·webpack
汤姆Tom28 分钟前
现代 CSS 架构与组件化:构建可扩展的样式系统
前端·css
偷光29 分钟前
浏览器中的隐藏IDE: Console (控制台) 面板
开发语言·前端·ide·php