【Vue中的Install方法】

255 阅读1分钟

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

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

这个是通过vue官方暴露出来的开发插件的install方法来实现的。 官方的解释为:

Vue.js的插件应该暴露一个install方法。这个方法的第一个参数是Vue,第二个参数是一个可选的选项对象。
MyPlugin.install = function(Vue,options){
//添加全局方法或property
Vue.myGlobalMethod = function(){
    ...
    }
}

接下来,我们尝试一下封装自己的工具类。
首先创建一个JS文件,假设命名为tools.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 = [...]  
    //尝试调用一下深拷贝方法。
    this.customerTools.deepClone(array)  
},