封装一个三方组件的通用套路
coderzhouyu2021-07-22 14:09
属性封装
$attrs
: 包含了父作用域中不作为 prop
被识别 (且获取) 的 attribute 绑定 (class 和 style 除外) 。当一个组件没有声明任何prop
时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs"
传入内部组件
inheritAttrs
设置为false
,避免给myInput组件设置的属性被添加到myInput组件的根元素div上。
//myInput.vue
<template>
<div>
<el-input v-model="input" v-bind="$attrs"></el-input>
</div>
</template>
<script>
export default {
// 避免给当前组件的属性因为 $attrs 传递到 el-input 去
inheritAttrs: false,
props: {
value: {
type: String,
default: '',
},
},
computed: {}
}
</script>
封装事件
$listeners
:包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件。
//myInput.vue
<template>
<div>
<el-input v-model="input" v-on="$listeners"></el-input>
</div>
</template>
这个封装可以把 el-input 传递出来的事件向上传递
封装插槽
插槽就没啥办法了,抄原来组件的插槽了只能
//myInput.vue
<template>
<div>
<el-input v-model="input" v-bind="$attrs" @blur="blur">
<template #prepend>
<slot name="prepend"></slot>
</template>
</el-input>
</div>
</template>
组件方法封装
组件上的方法也没好的办法,直接把封装的组件通过 ref 绑定到当前组件的属性上,上下文中链式调用即可
//myInput.vue
<template>
<div>
<el-input ref="elInput></el-input>
</div>
</template>
<script>
export default {
mounted(){
this.elInput = this.$refs.elInput;
}
}
</script>
使用示例
<template>
<div>
<myInput ref="myInput"></myInput>
</div>
</template>
<script>
import myInput from './myInput.vue';
export default {
data() {
return {}
},
components: {
myInput,
},
mounted() {
//调用el-input组件的focus方法
this.$refs.myInput.elInput.focus();
}
}
</script>
参考链接
https://juejin.cn/post/6943534547501858824