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