解决 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 改写
  // 
  //   function handleVisible(visible: boolean) {
  //     emit('update:dialogVisible', visible);
  //   }
  
</script>

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