解决 Unexpected mutation of “XXX” prop vue/no-mutating-props

解决 Unexpected mutation of “XXX” prop vue/no-mutating-props
普通属性直接使用 computed
v-model 两种方案

父组件

<Dialog :title="title" v-model:dialogVisible="dialogVisible" :form="form" />

子组件

<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" draggable>
    <el-form
      label-position="left"
      :model="dialogForm"
    >
      <el-form-item label="职级名称" prop="name" required>
        <el-input v-model="dialogForm.name" placeholder="请输入职级名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed } from 'vue';

  import { ListItem } from '@src/store/modules/rank';
  
  defineOptions({ name: 'RankDialog' });

  interface Props {
    title: string;
    dialogVisible: boolean;
    form: ListItem;
  }
  interface Emits {
    (e: 'update:dialogVisible', dialogVisible: boolean): void;
  }

  const props = withDefaults(defineProps<Props>(), {
    dialogVisible: false,
  });
  const emit = defineEmits<Emits>();

  // 普通属性
  const dialogTitle = computed(() => props.title);
  const dialogForm = computed(() => props.form);
  
  const handleCancel = () => {
    emit('update:dialogVisible', false);
  };

  // 方案一 利用 get set
  const dialogVisible = computed({
    get() {
      return props.dialogVisible;
    },
    set(visible: boolean) {
      emit('update:dialogVisible', visible);
    },
  });

  // 方案二 v-model 改写
  // <el-dialog :model-value="props.dialogVisible" @update:model-value="handleVisible" :title="dialogTitle">
  //   function handleVisible(visible: boolean) {
  //     emit('update:dialogVisible', visible);
  //   }
  
</script>

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值