教你用vue的install方法来创建工具类函数及全局组件

851 阅读2分钟

我们在利用vue的cli来做开发的时候,我们会引入一些框架以及各种插件,我们经常能看到类似于

Vue.use(Element, {
  size: Cookies.get('size') || 'medium'
})
Vue.use(Vant)

这样的代码,老弟,牛X哈,这代码一看就高大上呀。 实际上,这个是通过vue官方暴露出来的开发插件的install方法来实现的,下面我弟弟就教你如何来实现这种“牛X”操作. 我们先来看官网给出的install解释

image.png 看起来也不过如此嘛,让我们手动操作一下! 我们先来进行工具类的封装 首先呢,我们在我们的utils(你随意开心命名)文件夹下定义一个叫tools.js的js文件 然后呢。

//tools.js
const exampleFunc {
  install (Vue, options) {
    Vue.prototype.customerTools = {
     //这里随便粘贴了两个方法作为示例		
     //深度拷贝
     deepClone(source) {
			if (!source && typeof source !== 'object') {
				throw new Error('error arguments', 'shallowClone');
			}
			const targetObj = source.constructor === Array ? [] : {};
			for (const keys in source) {
				if (source.hasOwnProperty(keys)) {
					if (source[keys] && typeof source[keys] === 'object') {
						targetObj[keys] = source[keys].constructor === Array ? [] : {};
						targetObj[keys] = deepClone(source[keys]);
					} else {
						targetObj[keys] = source[keys];
					}
				}
			}
			return targetObj;
		},
		
		//获取网页url?后面的参数值
		getQueryString(name) {
		  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
		  var r = window.location.search.substr(1).match(reg);
		  if (r != null) {
		    return unescape(r[2]);
		  }
		  return null;
		}
		
  }
}
export default exampleFunc 

至此,我们的工作进行了99%,剩下那1%,我们在src/main.js文件里面进行,这个是我们程序的入口文件,主要是用来加载各种公共组件和方法的

//main.js
import exampleFunc from './utils/tools'
Vue.use(exampleFunc)
//好了,没啦。是不是看起来很简单?

接下来我们就在各种页面里调用方法就可以啦

//example.vue
mounted() {
let array = [...]
    //尝试调用一下深拷贝方法,ok!
    this.customerTools.deepClone(array)
},

工具类函数被我们成功送上天了。下面就剩组件了,到这里,怎么利用install创建全局组件我们是不是心里都有点笔数了,一奶同胞呀。 我们创建一个a.vue在main.js同级的文件夹views下

//a.vue
<template>
    <div>
        组件
    </div>
</template>
 
<script>
    export default {
 
    }
</script>
 
<style scoped>
   
</style

然后呢,我们在统计文件夹下创建一个js文件,就叫a-export.js

//a-export.js
import acomponent from './Cmponent.vue'
const avue = {
	install (Vue,options) {
		Vue.component('a-vue',acomponent)//前面的a-vue就是我们后面使用的组件名称,后面的acomponent是我们导入的组件文件
	}
}
export default avue

然后呢,跟我们创建工具类方法引用一样

//main.js
import avue from './views/a-export.js'
Vue.use(avue)

然后你页面就可以使用这个avue组件啦

//某某某.vue
<template>
  <div>
    <a-vue><a-vue>
  </div>
</template>

装逼完毕,吕某人吃饭去了~~~~感觉对您有用的麻烦给个小心心,谢谢!