VUE 之 封装自己的vue插件

大家好!我叫戴向天

QQ群:602504799

如若有不理解的,可加QQ群进行咨询了解

写自己的vue插件的好处是,方便调用,方便管理,可以随处使用,甚至不管哪个项目都可以使用.并且调用的方法也很简单:this.xxxx()

第一步: 创建vue-plugIn.js文件(名字可自定义:例如:Clover-vue-plugIn.js。自己方便记住就好)
内容:

// 根据需求进行引入
import efficacy from './efficacy'		// 效验方法
import cache from './localStorage'	// 缓存方法
import { Dialog } from 'vant'		// vant的方法
import PlatformConfig from './platformConfig'		// 自己项目配置
import { backendPath, port, ProjectName } from './base'	// 自己基础配置
const PlugIn = {}

PlugIn.install = function (Vue, option) {
  Vue.mixin({
    methods: {
      $Dialog: Dialog,
      $confirm: Dialog.confirm,
      efficacy,
      cache: () => cache,
      getType (o, s) {
        let t = Object.prototype.toString.call(o).split(' ')[1]
        t = t
          .substring(0, t.length - 1)
          .trim()
          .toLowerCase()
        if (
          t === 'object' &&
          Object.prototype.toString.call(o).toLowerCase() ===
          '[object object]' &&
          !o.length
        ) { t = 'json' }
        return s ? t === s : t
      },
      getUrl (url) {
        return `${backendPath}${port}/${ProjectName}/picture/${url}`
      },
      goPage (url, params) {
        this.$router.push(url, params)
      },
      goBack () {
        this.$router.go(-1) // 返回上一层
      },
      getLinkMap () {
        return PlatformConfig.links
      }
    }
  })
}

export default PlugIn

第二步:引入

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import PlugIn from '@/assets/libs/vue-plugIn'		// 引入自己写的插件
Vue.use(PlugIn)	//进行使用
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

使用:

const type = this.getType("VUE 之 封装自己的vue插件“)
console.log("type=>",type)

猜你喜欢

转载自blog.csdn.net/weixin_41088946/article/details/106048740