Vue.use 和 Vue.prototype.$xx 的区别

Vue.use

举例:

首先引入api

1
2
import api from './api/index'
Vue.use(api);

再看下api/index.js中的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import request from '../utils/request'

export default {
install(Vue, options) {
Vue.prototype.get = function(url, params) {
return request({
url: url,
method: 'get',
params: params
})
};

Vue.prototype.post = function(url, data) {
return request({
url: url,
method: 'post',
data
})
}
}
}

可以发现其中有一个install函数,它是本文的主角,Vue.use就是要运行这个install函数。

总结
  1. Vue的插件是一个对象,就像Element
  2. 插件对象必须有install
  3. install字段是个函数
  4. 初始化插件对象需要Vue.use()
  5. Vue.use()调用必须在new Vue之前
  6. 同一个插件多次使用Vue.use()也只会被运行一次

Vue.prototype.$xx

本质其实就是js中的函数原型的特性:函数原型上的属性/方法, 在函数实例化后, 可以在任意实例上读取。

1
2
3
4
5
6
7
/**
* moment 时间组件
* 使用 this.$moment() 调用
*/
import moment from 'moment'
moment.locale('zh-cn');
Vue.prototype.$moment = moment;