vue-插件

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
  }
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值