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值