目录
这篇文章主要介绍了 Vue 子组件内的 props 对象里的 default 参数是如何定义
Array 、Object 、或 Function 默认值的正确写法说明,具有很好的参考价值
正确写法 :
- props: {
- demoBoo: {
- type: Boolean,
- default: true,
- },
- },
正确写法 :
- props: {
- demoNum: {
- type: Number,
- default: 1,
- },
- },
正确写法 :
- props: {
- demoStr: {
- type: String,
- default: 'hello',
- },
- },
错误写法 :
- props: {
- demoArr: {
- typeof: Array,
- default: [],
- },
- },
Eslint 语法报错 :
Invalid default value for prop “demo”: Props with type Object/Array must use a factory function to return the default value.
正确的常规写法 :
- props: {
- demoArr: {
- type: Array,
- default: function () {
- return [];
- },
- },
- },
或是用 箭头函数 :
- props: {
- demoArr: {
- type: Array,
- default: () => [],
- },
- },
错误写法 :
- props: {
- demoObj: {
- type: Object,
- default: () => {},
- },
- },
正确的常规写法 :
- props: {
- demoObj: {
- type: Object,
- default: function () {
- return {};
- },
- },
- },
或是用 箭头函数 : ( 注意 : 这里的对象一定要用小括号包裹起来 ( { } ) )
- props: {
- demoObj: {
- type: Object,
- default: () => ({}),
- },
- },
正确写法 :
- props: {
- demoFun: {
- type: Function,
- default: () => {},
- },
- },
补充知识 :Vue 传参 props 里面为什么要带 type , 还有 default ?
这个是 子组件 , 写 type 的 意思 是 swiperDate 传过来的 数据类型 是 数组 ,
default 就是 表示 不传 , 默认 返回 的 [ ] , 空数组 .
这种就是 表示 传的 数据类型 是 Number , 不传 默认 是 数字 0 。