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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM