使用vue公开方法 install创建公共方法或变量


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值

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM