Vue报错:Invalid prop: type check failed for prop “roleList“. Expected Object, got Array 解决方法

说明:该篇博客是博主一字一码编写的,实属不易,请尊重原创,谢谢大家!

问题描述

Vue 项目中通过 Props 属性向子组件传值的时候,很多小伙伴经常遇到Invalid prop: type check failed for prop “roleList”. Expected Object, got Array 的错误信息

在这里插入图片描述

先看看父组件和子组件传递的代码,这里注意看两个组件之间通过 Props 属性传值所定义的类型

父组件:

<template>
  <div class="app-container">
    <add-user-dialog
      :role-list="roleList"
    />
  </div>
</template>
export default {
    
    
  data() {
    
    
    return {
    
    
      roleList: [] // 角色列表
    }
  }
}

子组件:

export default {
    
    
  props: {
    
    
    roleList: {
    
    
      type: Object, // 类型
      default: null // 默认值
    }
  }
}

解决方法

根据以上可以看到我们在父组件向子组件传递的 roleList 变量的类型是数组,而在子组件中 roleList 变量的类型是对象,所以出现了错误:在子组件中我们的期望是一个对象,而你父组件中给我传递了一个数组,这就是导致错误的原因,修改 Props 属性的 roleList 变量的类型和默认值即可

export default {
    
    
  props: {
    
    
    roleList: {
    
    
      type: Array, // 类型
      default: () => [] // 默认值
    }
  }
}

问题解决,所以大家在写代码的时候特别是传递参数时,注意两边参数定义的类型是否一致!

猜你喜欢

转载自blog.csdn.net/qq_41782425/article/details/132202943