vue3 composition api使用v-model封装el-dialog

只贴上精简代码

父组件

父组件使用v-model绑定子组件,会默认传递一个modelValue变量和update:modelValue方法到子组件

<customDialog
   v-model="customDialogVisible "
>customDialog>

子组件

 <el-dialog
      v-model="dialogVisible "
      ...
    >
    ...

defineEmitsdefineEmits定义modelValue变量和update:modelValue方法
vue语法中不应直接修改props(一些旧版本中直接修改是可以正常运行的,但新版本严格限制,直接报错),所以子组件中v-model不应绑定modelValue,所以用computed生成一个变量用于v-model绑定

<script lang="ts" setup>
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";

const props = defineEmits<{
  modelValue: boolean;
}>();

const emits = defineEmits<{
  (e: "update:modelValue", t: boolean): void;
}>();

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (newValue) => {
    emits("update:modelValue", newValue);
  },
});
...

你可能感兴趣的:(vue.js,javascript,前端)