当前位置:Gxlcms > JavaScript > 详解Vue.use自定义自己的全局组件

详解Vue.use自定义自己的全局组件

时间:2021-07-01 10:21:17 帮助过:53人阅读

通常我们在vue里面使用别人开发的组件,第一步就是install,第二步在main.js里面引入,第三步Vue.use这个组件。今天我简单的也来use一个自己的组件。

这里我用的webpack-simple这个简单版本的脚手架为例,安装就不啰嗦了,直接进入正题

首先看下目前的项目结构:

webpack首先会加载main.js,所以我们在main的js里面引入。我以element ui来做对比说明

  1. import Vue from 'vue'
  2. import App from './App.vue'
  3. // 引入element-ui组件
  4. import ElementUi from 'element-ui'
  5. import 'element-ui/lib/theme-default/index.css'
  6. // 引入自定义组件。index.js是组件的默认入口
  7. import Loading from '../components/loading'
  8. Vue.use(Loading);
  9. Vue.use(ElementUi);
  10. new Vue({
  11. el: '#app',
  12. render: h => h(App)
  13. })

然后在Loading.vue里面定义自己的组件模板

  1. <!-- 这里和普通组件的书写一样 -->
  2. <template>
  3. <div class="loading">
  4. loading...
  5. </div>
  6. </template>

在index.js文件里面添加install方法

  1. import MyLoading from './Loading.vue'
  2. // 这里是重点
  3. const Loading = {
  4. install: function(Vue){
  5. Vue.component('Loading',MyLoading)
  6. }
  7. }
  8. // 导出组件
  9. export default Loading

接下来就是在App.Vue里面使用组件了,这个组件已经在main.js定义加载了

  1. <template>
  2. <div id="app">
  3. <!-- 使用element ui的组件 -->
  4. <el-button>默认按钮</el-button>
  5. <!-- 使用自定义组件 -->
  6. <Loading></Loading>
  7. </div>
  8. </template>

下面是效果图

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行