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>

相关推荐
晚霞的不甘1 小时前
Flutter for OpenHarmony天气卡片应用:用枚举与动画打造沉浸式多城市天气浏览体验
前端·flutter·云原生·前端框架
weixin79893765432...1 小时前
Vue 渲染体系“三件套”(template 模板语法、h 函数和 JSX 语法)
vue.js·h函数·template 模板·jsx 语法
xkxnq2 小时前
第五阶段:Vue3核心深度深挖(第74天)(Vue3计算属性进阶)
前端·javascript·vue.js
三小河2 小时前
Agent Skill与Rules的区别——以Cursor为例
前端·javascript·后端
Hilaku2 小时前
不要在简历上写精通 Vue3?来自面试官的真实劝退
前端·javascript·vue.js
三小河2 小时前
前端视角详解 Agent Skill
前端·javascript·后端
Aniugel2 小时前
单点登录(SSO)系统
前端
颜酱2 小时前
二叉树遍历思维实战
javascript·后端·算法
鹏多多2 小时前
移动端H5项目,还需要react-fastclick解决300ms点击延迟吗?
前端·javascript·react.js
serioyaoyao2 小时前
上万级文件一起可视化,怎么办?答案是基于 ParaView 的远程可视化
前端