天天看點

vue自定義元件全局注冊

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)
})
           

繼續閱讀