在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/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í)使用的過程中,都實現(xiàn)了數(shù)據(jù)調(diào)用
想知道這兩者的區(qū)別

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

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

vm.api()

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

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

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

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

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

然后我們要注冊這個插件

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

Vue.use(say)

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

我們來看Vue.use方法內(nèi)部是怎么實現(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;
};

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

2017年12月7日 13:57