大家好!我叫戴向天
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)