Vue.use()的用法和install的用法解析
Vue.use()和install用法
介紹
在vue的main.js中,我們經(jīng)常使用Vue.use(xx)方法。比如我們引入elementUI,在main.js中,我們一般通過如下代碼引入:
import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI)
為什么這樣做?
官方解釋
安裝 Vue.js 插件。如果插件是一個對象,必須提供 install 方法。如果插件是一個函數(shù),它會被作為 install 方法。
install 方法調用時,會將 Vue 作為參數(shù)傳入。什么意思呢? Vue.use() 中的參數(shù)必須是一個function函數(shù)或者是一個Object對象,如果是對象的話,必須在對象中提供一個install方法。之后會將 Vue 作為參數(shù)傳入。
總結:
如果Vue.use() 中的參數(shù)是一個function函數(shù),那么函數(shù)的參數(shù)是Vue對象。
如果Vue.use() 中的參數(shù)是一個Object對象,那么這個對象必須提供一個install方法,install方法的參數(shù)就是Vue。
Vue.use為什么要使用install
疑問
Vue.use注冊插件和Vue.prototype.xxx掛載方式有什么區(qū)別,使用Vue.use優(yōu)勢在哪,為什么使用Vue.use而不使用Vue.prototype.xxx
從源碼分析
// Vue源碼文件路徑:src/core/shared/util.js
export function toArray (list: any, start?: number): Array<any> {
start = start || 0
let i = list.length - start
const ret: Array<any> = new Array(i)
while (i--) {
ret[i] = list[i + start]
}
return ret
}
// Vue源碼文件路徑:src/core/global-api/use.js
import { toArray } from '../util/index'
export function initUse (Vue: GlobalAPI) {
Vue.use = function (plugin: Function | Object) {
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
if (installedPlugins.indexOf(plugin) > -1) { // 如果該插件已被注冊,則不再進行注冊
return this
}
// additional parameters
const args = toArray(arguments, 1)
args.unshift(this)
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}
installedPlugins.push(plugin)
return this
}
}
vue官網(wǎng)是這樣說的

install方法應該就是解決防止插件多次注冊的情況吧;如果使用Vue.prototype.xxx掛載,每使用一次就要重新掛載一次。
個人理解,還請大佬指正解釋一下install的優(yōu)勢
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
elementui 開始結束時間可以選擇同一天不同時間段的實現(xiàn)代碼
這篇文章主要介紹了elementui 開始結束時間可以選擇同一天不同時間段的實現(xiàn)代碼,需要先在main.js中導入相應代碼,代碼簡單易懂,需要的朋友可以參考下2024-02-02
vue3數(shù)據(jù)可視化實現(xiàn)數(shù)字滾動特效代碼
這篇文章主要介紹了vue3數(shù)據(jù)可視化實現(xiàn)數(shù)字滾動特效,實現(xiàn)思路是使用Vue.component定義公共組件,使用window.requestAnimationFrame(首選,次選setTimeout)來循環(huán)數(shù)字動畫,詳細代碼跟隨小編一起看看吧2022-09-09
前端vue面試總問watch和computed區(qū)別及建議總結
在現(xiàn)代前端的面試中,vue和react是面試過程中基本必問的技術棧,其中Vue響應式話題,watch和computed是面試官非常喜歡聊的主題,雖然watch和computed它們都用于監(jiān)聽數(shù)據(jù)的變化,但它們在實現(xiàn)原理、使用場景和行為上有著顯著的區(qū)別,本文將深入探討,并提供一些面試過程中的建議2023-10-10
使用vue.js實現(xiàn)checkbox的全選和多個的刪除功能
這篇文章主要介紹了使用vue.js實現(xiàn)checkbox的全選和多個的刪除功能,需要的朋友可以參考下2017-02-02

