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 小时前
移动端触摸事件与鼠标事件的触发机制详解
前端·javascript
人工智能训练师7 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny077 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy8 小时前
css的基本知识
前端·css
昔人'8 小时前
css `lh`单位
前端·css
前端君9 小时前
实现最大异步并发执行队列
javascript
Nan_Shu_61410 小时前
Web前端面试题(2)
前端
知识分享小能手10 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
蚂蚁RichLab前端团队11 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光11 小时前
css之一个元素可以同时应用多个动画效果
前端·css