Vue.use() 和 Vue.component() 的區別


官方定義:

Vue.use( plugin )

  • 參數:

    • {Object | Function} plugin
  • 用法:

    安裝 Vue.js 插件。如果插件是一個對象,必須提供 install 方法。如果插件是一個函數,它會被作為 install 方法。install 方法調用時,會將 Vue 作為參數傳入。

    該方法需要在調用 new Vue() 之前被調用。

    當 install 方法被同一個插件多次調用,插件將只會被安裝一次。

  • 參考:插件

Vue.component( id, [definition] )

  • 參數:

    • {string} id
    • {Function | Object} [definition]
  • 用法:

    注冊或獲取全局組件。注冊還會自動使用給定的 id 設置組件的名稱

    // 注冊組件,傳入一個擴展過的構造器 Vue.component('my-component', Vue.extend({ /* ... */ })) // 注冊組件,傳入一個選項對象 (自動調用 Vue.extend) Vue.component('my-component', { /* ... */ }) // 獲取注冊的組件 (始終返回構造器) var MyComponent = Vue.component('my-component')
  • 參考:組件

2、當我們想好多地方要是用到同一個組件,又不想每次都在局部注冊時,可以在main.js 中全局注冊

main.js

import common from '@/components/common.vue'

Vue.component(common);

3、Vue.use() 可以一次性注冊多個組件或添加全局方法或屬性

Vue.use(plugin)的初始化方法{install:function(){}}里面可以一次性注冊多個組件。
Vue.component只能一個一個注冊。
install可以做更多的事情
MyPlugin.install=function(Vue,options){
//1.添加全局方法或屬性
Vue.myGlobalMethod=function(){
//邏輯...
}
//2.添加全局資源
Vue.directive('my-directive',{
bind(el,binding,vnode,oldVnode){
//邏輯...
}
...
})
//3.注入組件選項
Vue.mixin({
created:function(){
//邏輯...
}
...
})
//4.添加實例方法
Vue.prototype.$myMethod=function(methodOptions){
//邏輯...
}
}

 


免責聲明!

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



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