Vue.use自定義自己的全局組件


 通常我們在vue里面使用別人開發的組件,第一步就是install,第二步在main.js里面引入,第三步Vue.use這個組件。今天我簡單的也來use一個自己的組件。

這里我用的webpack-simple這個簡單版本的腳手架為例,安裝就不啰嗦了,直接進入正題

首先看下目前的項目結構:

webpack首先會加載main.js,所以我們在main的js里面引入。我以element ui來做對比說明

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

// 引入element-ui組件
import ElementUi from 'element-ui'
import 'element-ui/lib/theme-default/index.css'

// 引入自定義組件。index.js是組件的默認入口
import Loading from '../components/loading'
Vue.use(Loading);

Vue.use(ElementUi);
new Vue({
  el: '#app',
  render: h => h(App)
})

然后在Loading.vue里面定義自己的組件模板

<!-- 這里和普通組件的書寫一樣 -->
<template>
    <div class="loading">
        loading...
    </div>
</template>

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

import MyLoading from './Loading.vue'
// 這里是重點
const Loading = {
    install: function(Vue){
        Vue.component('Loading',MyLoading)
    }
}

// 導出組件
export default Loading

接下來就是在App.Vue里面使用組件了,這個組件已經在main.js定義加載了

<template>
  <div id="app">
  <!-- 使用element ui的組件 -->
  <el-button>默認按鈕</el-button>

  <!-- 使用自定義組件 -->
  <Loading></Loading>
  </div>
</template>

下面是效果圖


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM