Vue 自定义全局UI组件

  • 在Vue开发中经常使用第三方插件,通过在 main.js 文件中 使用 Vue.use() 导入后就可以随意在任何 vue 页面进行使用这个组件,那么如果自己做一个呢?

一、在当前Vue项目中任意位置建一个组件文件夹

  • custom.vue:是自定义的组件UI,文件名随意,可以多个
  • index.js:文件名推荐固定写法,后期只需要链接到文件夹,默认读取 index.js 文件

custom.vue :

<template>
  <div class="custom-view">自定义UI组件详情</div>
</template>

<script>
export default {
  // 这里可以添加 name 字段,到时候在 index.js 文件里面导入的时候可以直接导入插件名称即可
  // name: 'custom'
}
</script>

<style scoped>
.custom-view {
  width: 100px;
  height: 100px;
  background-color: red;
}
</style>

index.js :

// 导入自定义组件
import CustomView from './custom.vue'
// ...... 可以导入更多自定义组件

const Custom = {
  // 主要是这个方法
  install: function (Vue) {
    Vue.component('Custom', CustomView)
    // Vue.component(CustomView.name, CustomView)
    // 如果存在多个自定义组件,直接头部多次 import 进来,然后这里多次导入
    // Vue.component('More', More)
  }
}

export default Custom

二、main.js 导入刚才自定义的组件

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

// 通过 Vue.use() 导入即可,看文件链接 './custom' 默认会读取里面的 index.js
// 推荐文件夹里面自带 index.js 文件
import Custom from './custom'
Vue.use(Custom)

// 如果 custom 文件假里面没有 index.js 这个名字的文件
// 则需要手动补全,比如我将文件里面的 index.js 改成 index1.js,则需要这样导入
// import Custom from './custom/index1'
// Vue.use(Custom)

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

三、进行使用这个导入的全局组件

  • 任意找一个可显示页面直接使用 <custom></custom> 组件
<template>
  <custom></custom>
</template>

<script>
export default {

}
</script>

<style>

</style>

自定义全局组件到这来就完成了!!!


其他扩展资料
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卡尔特斯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值