鍍金池/ 問答/HTML/ 關(guān)于Vue.prototype 和vue.use()的疑問

關(guān)于Vue.prototype 和vue.use()的疑問

vue新手,經(jīng)常在main.js中看到
Vue.prototype.$xxx = xxx;

clipboard.png

和使用vue.use()

clipboard.png

clipboard.png
api.js

clipboard.png

我在學(xué)習(xí)使用的過程中,都實(shí)現(xiàn)了數(shù)據(jù)調(diào)用
想知道這兩者的區(qū)別

回答
編輯回答
風(fēng)畔

首先,不管你采用哪種方式,最終實(shí)現(xiàn)的調(diào)用方式都是

vm.api()

也就是說,兩種方法,實(shí)現(xiàn)的原理都是在Vue.prototype上添加了一個(gè)方法。所以結(jié)論是“沒有區(qū)別”。

再來說說Vue.use()到底干了什么。

我們知道,Vue.use()可以讓我們安裝一個(gè)自定義的Vue插件。為此,我們需要聲明一個(gè)install函數(shù)

// 創(chuàng)建一個(gè)簡(jiǎn)單的插件 say.js
var install = function(Vue) {
  if (install.installed) return // 如果已經(jīng)注冊(cè)過了,就跳過
  install.installed = true

  Object.defineProperties(Vue.prototype, {
    $say: {
      value: function() {console.log('I am a plugin')}
    }
  })
}
module.exports = install

然后我們要注冊(cè)這個(gè)插件

import say from './say.js'
import Vue from 'vue'

Vue.use(say)

這樣,在每個(gè)Vue的實(shí)例里我們都能調(diào)用say方法了。

我們來看Vue.use方法內(nèi)部是怎么實(shí)現(xiàn)的

Vue.use = function (plugin) {
  if (plugin.installed) {
    return;
  }
  // additional parameters
  var args = toArray(arguments, 1);
  args.unshift(this);
  if (typeof plugin.install === 'function') {
    plugin.install.apply(plugin, args);
  } else {
    plugin.apply(null, args);
  }
  plugin.installed = true;
  return this;
};

其實(shí)也就是調(diào)用了這個(gè)install方法而已。

2017年12月7日 13:57