通常我們在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>
下面是效果圖
文章轉自:https://www.cnblogs.com/yesyes/p/6658611.html