Vue.js
插件
插件通常是用来给 vue
提供扩展功能的一种方式
- 给
Vue
添加属性和方法 - 给
Vue 实例
添加属性和方法 - 添加全局资源:指令、过滤器、组件等
- 添加配置选项
安装插件
通过全局方法 Vue.use()
使用插件。它需要在调用 new Vue()
启动应用之前完成
Vue.use(插件);
如果插件是一个对象,必须提供 install
方法。如果插件是一个函数,它会被作为 install
方法。install
方法调用时,会将 Vue 作为参数传入
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) {
// 逻辑...
}
}
实例
axios
https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.min.js
function http(_Vue, options) {
_Vue.prototype.$http = axios;
}
Vue.use(http);
// or
function http(_Vue, options) {
_Vue.prototype.$http = adaptor.http;
}
Vue.use(http, {adaptor: axios});
new Vue({
el: '#app',
data: {
},
async created() {
// let rs = await axios({
// method: 'post',
// url: 'https://api.apiopen.top/musicRankings'
// });
// console.log(rs);
let rs = await this.$http({
method: 'post',
url: 'https://api.apiopen.top/musicRankings'
});
console.log(rs);
}
});
修改
prototype
会修改整个Vue
原型链
另外一种方式
function http(_Vue) {
_Vue.mixin({
beforeCreate() {
if ( this.$options.adaptor ) {
this.$http = this.$options.adaptor;
}
if ( this.$options.parent && this.$options.parent.$http ) {
this.$http = this.$options.parent.$http;
}
}
});
}
Vue.use(http);
new Vue({
el: '#app',
adaptor: axios,
components: {
'my-component': myComponent
}
})