Vue 使用use、prototype自定义自己的全局组件

使用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中使用

原文地址:https://www.cnblogs.com/conglvse/p/9667132.html