使用Vue.use()
寫一個自己的全局組件。
目錄如下:
然后在Loading.vue里面定義自己的組件模板
<template>
<div v-if="loadFlag">
Loading...
</div>
</template>
<script>
export default {
name: "MyLoading",//組件名稱
props: ['loadFlag'],
}
</script>
在loading文件夾下的index.js文件里面添加install方法
import Loading from './Loading.vue'
Loading.install=function(Vue){
Vue.component(Loading.name,Loading) //組件名稱取組件的name
}
export default Loading //導出組件
main.js
// 引入自定義組件。index.js是組件的默認入口
import Loading from '../components/common/loading'
Vue.use(Loading);
接下來就是在頁面里面使用組件了,這個組件已經在main.js定義加載了
<template>
<div id="app">
<!-- 使用自定義組件 -->
<my-loading></my-loading>
</div>
</template>
<script>
export default {
data() {
return {
loadFlag: true,
}
},
created: function () {
this.getTableData();
},
methods: {
getTableData() {
this.$http.post('.../').then(res => {
...
this.loadFlag = false;
});
}
}
}
</script>
message組件和loading有所不同,使用Vue.prototype.$my_message = Message.install
方法導入,調用時直接使用this.$my_message('這是一個message')
,可參考“Vue 自定義全局消息框組件”
所有的全局組件也可在一個js里定義,然后在main.js全局使用
如下圖是common文件夾下的index.js
main.js中使用