场景
当我们试使用某一组件库,或者其他不能修改或者不建议修改的组件时, 如vant的button组件,它默认type为default,我要让他type默认为primary的话,每次都要传入type参数
主要按钮1
主要按钮2
主要按钮3
那如果我想不传参数就让它type为primary的话,通常的做法就是再写个组件封装一下,如: t4.vue
默认按钮
import cVanButton from './c-van-button'
export default {
name: "t4",
components: {
cVanButton
}
}
c-van-button.vue
export default {
name: "c-van-button",
inheritAttrs: false,
props: {
type: {
type: String,
default: 'primary'
}
}
}
问题
以上方法虽然简单的实现了type默认为primary,但是,如果需要在传入其他参数呢
默认按钮
c-van-button.vue是不是要这样写
export default {
name: "c-van-button",
inheritAttrs: false,
props: {
type: {
type: String,
default: 'primary'
},
size: {
type: String,
default: 'normal'
},
loading: {
type: Boolean,
default: false
}
}
}
如果参数很多呢,是不是也要一个一个写呢
很显然,这并不是一个完美的解决方法
使用inheritAttrs,vm. a t t r s , v m . attrs,vm. attrs,vm.listeners什么是inheritAttrs
https://cn.vuejs.org/v2/api/#inheritAttrs
https://cn.vuejs.org/v2/api/#vm-attrs
https://cn.vuejs.org/v2/api/#vm-listeners
解决方案t4.vue
默认按钮1
默认按钮2
默认按钮3
import cVanButton from './c-van-button'
export default {
name: "t4",
components: {
cVanButton
}
}
c-van-button.vue
export default {
name: "c-van-button",
inheritAttrs: false,
props: {
type: {
type: String,
default: 'primary'
}
}
}
效果
通过对组件的二次封装,声明默认参数,对其他参数用v-on="$listeners"
v-bind="$attrs"
的形式传入,并且声明inheritAttrs: false
,
未声明inheritAttrs: false
会同时将参数写入html自定义属性中