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>

相关推荐
满怀101526 分钟前
【Vue 3全栈实战】从响应式原理到企业级架构设计
前端·javascript·vue.js·vue
luckywuxn36 分钟前
使用gitbook 工具编写接口文档或博客
前端
梅子酱~1 小时前
Vue 学习随笔系列二十三 -- el-date-picker 组件
前端·vue.js·学习
伟笑1 小时前
elementUI 循环出来的表单,怎么做表单校验?
前端·javascript·elementui
辣辣y1 小时前
React中useMemo和useCallback的作用:
前端·react
Alice-YUE1 小时前
【HTML5学习笔记1】html标签(上)
前端·笔记·学习·html·html5
Alice-YUE1 小时前
【HTML5学习笔记2】html标签(下)
前端·笔记·html·html5
确实菜,真的爱1 小时前
electron进程通信
前端·javascript·electron
源码云商2 小时前
【带文档】网上点餐系统 springboot + vue 全栈项目实战(源码+数据库+万字说明文档)
数据库·vue.js·spring boot
!win !3 小时前
uni-app小程序登录后…
前端·uni-app