vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Unexpected mutation of “xxx“ prop

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

作者:jieyucx

这篇文章主要给大家介绍了关于如何解决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"不应该在子组件中直接双向绑定父组件传递过来的值

解决方案:

<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>
<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,搞个计算属性解决了

总结

到此这篇关于解决vue3报错:Unexpected mutation of “xxx“ prop.(eslintvue/no-mutating-props)的文章就介绍到这了,更多相关Unexpected mutation of “xxx“ prop内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文