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