vue3报错 Unexpected mutation of “xxx“ prop.(eslintvue/no-mutating-props)

vue3报错 Unexpected mutation of “xxx“ prop.(eslintvue/no-mutating-props)

在这里插入图片描述

eslint校验报这个错,其实是Vue的单向数据流的概念,因为识别到子组件中修改了props值

我这里踩到这个坑是这么操作的,我在父组件中给子组件传了个值,然后再子组件中v-modle这个值,于是就给我报了这个错!

复现场景如下:
父组件中

<enter-school ref="enterSchoolRef" :student-info="selectRows" />

子组件中

<template>
    <el-form ref="formRef" class="enterForm" inline :model="form" :rules="rules" @submit.prevent>
      <el-input
          v-model="studentInfo[0].name"
          clearable
          placeholder="请输入姓名"
        />
     </el-form>
</template>
<script>
    props: {
    
    
      studentInfo: {
    
    
        type: Array, //类型
        default: null //默认值
      },
    },
</script>

报错就在v-model="studentInfo[0].name"
不应该在子组件中直接双向绑定父组件传递过来的值
解决方案:

  1. 计算属性 依赖该props进行计算/转换
<template>
 <el-input
      v-model="studentName"
      clearable
      placeholder="请输入姓名"
 />
</template>
<script>
    import {
    
     computed } from 'vue'
    props: {
    
    
      studentInfo: {
    
    
        type: Array, //类型
        default: null //默认值
      },
    }
    setup(props) {
    
    
      const studentName = computed(() =>
        props.studentInfo &&
        props.studentInfo.length > 0 ? props.studentInfo[0].name : null
      )
      return {
    
    
          studentName 
     }
    }
</scirpt>
  1. 定义中间变量 在子组件内的定义一个变量,并将接收的props当作其初始值:
<template>
 <el-input
      v-model="studentName"
      clearable
      placeholder="请输入姓名"
 />
</template>
<script>
    import {
    
     computed, defineComponent, reactive, toRefs } from 'vue'
    props: {
    
    
      studentInfo: {
    
    
        type: Array, //类型
        default: null //默认值
      },
     }
    export default defineComponent({
    
    
    setup(props) {
    
    
      const state = reactive({
    
    
        studentName : props.studentInfo[0].name
      })
      return {
    
    
          ...toRefs(state),
     }
    }
   })
</scirpt>

我就是用的方案1,搞个计算属性解决了

猜你喜欢

转载自blog.csdn.net/jieyucx/article/details/128289829