vue使用install函數把組件做成插件方便全局調用


在vue項目中,我們可以自定義組件,像element-ui一樣使用Vue.use()方法來使用,具體實現方法:

1.首先新建一個Cmponent.vue文件

// Cmponent.vue
<template>
    <div>
        我是組件
    </div>
</template>
 
<script>
    export default {
 
    }
</script>
 
<style scoped>
    div{
        font-size:40px;
        color:#fbb;
        text-align:center;
    }
</style>


2.其次在同一目錄下建立index.js文件,在這個文件中使用install方法來全局注冊該組件

import component from './Cmponent.vue'
const component = {
    install:function(Vue){
        Vue.component('component-name',component)
    }  //'component-name'這就是后面可以使用的組件的名字,install是默認的一個方法
    
}
// 導出該組件
export default component


3.使用

// 只要在index.js里規定了install方法,就可以向其他ui組件庫那樣,使用Vue.use()來全局使用

// 只要在index.js里規定了install方法,就可以向其他ui組件庫那樣,使用Vue.use()來全局使用
import loading from './index.js'
 
Vue.use(loading)
 
<template>
   <div>
      <component-name></component-name>
   </div>    
</template>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM