Vue.js 的插件有一個公開方法 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) {
// 邏輯...
}
}
這里是我寫的方法 request.js
export default {
install(Vue) {
Vue.prototype.$request = new Vue({
data: {
z :"zhix.net"
},
methods: {
post(url,data) {
return new Promise((reslove, reject) => {
this.axios
.post(url, data)
.then(function (res) {
reslove(res.data);
})
.catch(function (err) {
if (err.response) {
reject(err.response)
}
});
});
},
get(url,data) {
return new Promise((reslove, reject) => {
this.axios
.post(url, data)
.then(function (res) {
console.log(res)
reslove(res.data);
})
.catch(function (err) {
if (err.response) {
reject(err.response)
}
});
});
}
}
})
Vue.prototype.$say = function (str) {
console.log(str)
}
}
}
main.js 里引入
// 導入自己的公共方法 import request from './lib/request.js' Vue.use(request);
任意組件使用
this.$request.post("/api/eoffice10/server/public/api/open-api/get-token", data).then(function(res){
console.log(res);
}) //使用post方法
this.$say(this.$bus.z) //使用$say方法 並取data z值
