Vue之插件使用

插件通常会为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) {
    // 逻辑...
  }

使用插件

// 通过全局方法 Vue.use() 使用插件
//调MyPlugin.install(Vue)
Vue.use(MyPlugin)

//传入一个选项对象
Vue.use(MyPlugin, { someOption: true })
import Vue from 'vue'
import App from './App'
import MintUI from 'mint-ui'
import 'mint-ui/lib/style.css'
import VueAwesomeSwiper from 'vue-awesome-swiper'
import RegionPicker from 'vue-region-picker'
import CHINA_REGION from 'china-area-data'
import router from './router'
import store from './store'
import axios from 'axios'
Vue.use(MintUI)
Vue.use(VueAwesomeSwiper)
Vue.use(RegionPicker, {
  region: CHINA_REGION,
  vueVersion: 2
})

1. Vue.use会自动阻止注册相同插件多次,只会注册一次该插件。
2. 一些插件(如vue-router)如果Vue是全局变量则自动调用Vue.user()

猜你喜欢

转载自blog.csdn.net/zn740395858/article/details/76132630