vue自定义组件全局注册----(vue.use() )install的使用
在vue项目中我们可以自定义组件,通过install全局注册
1、首先创建一个index.vue文件
ps:
<template>
<div class="btn-wrapper">
<el-button :class="['btnItem',item.class]"
v-for="(item, index) in btnConfig"
:type="item.type"
:disabled="disabledItems.includes(item.name)"
@click="handleClick(item.cb)"
:key="index"><span :class="['iconfont',iconClass[item.name]]"></span>{{ item.label }}</el-button>
</div>
</template>
<script>
import { iconClass } from './constant.js'
export default {
name: 'btnWrapper',
data () {
return {
iconClass
}
},
props: {
btnConfig: {
type: Array,
default: () => []
},
disabledItems: {
type: Array,
default: () => []
},
owner: {
type: Object,
default: () => { }
}
},
methods: {
// 按钮的点击事件
handleClick (cb) {
cb && cb(this.owner)
},
// 动态获取按钮组的宽度
getWidth () {
const tablePanel = document.querySelector('.table-panel')
let arr = tablePanel.querySelectorAll('.btnItem')
let width = 0
for (let i = 0; i < this.btnConfig.length; i++) {
if (arr[i]) {
width += arr[i].offsetWidth + 2
}
}
return width + 20
}
},
mounted () {
this.$emit('setBtnWidth', this.getWidth())
}
}
</script>
<style lang="scss" scoped>
</style>
2、在同一目录下建立entry.js文件,在该文件中使用install方法全局注册该组件
import btnWrapper from ‘./index.vue’
btnWrapper.install = function (Vue) {
Vue.component(btnWrapper.name, btnWrapper)
}
//导出该组件`在这里插入代码片`
export default btnWrapper
3、使用
导出组件:components文件夹下创建文件index.js
import btnWrapperfrom './btnWrapper/entry.js'
export default btnWrapper
在main.js中引入相应的文件并用vue.compoment()全局注册
import Components from '@/components/index.js'
Components.forEach(component => {
Vue.use(component)
})