本文主要是介绍Vue解析一之挂载全局变量与方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、在mian.js里面进行Vue对象的原型连的挂载Vue.prototype.$ajax = Ajax;
2、使用Mixin:
VuVue.mixin({data(){return {Host:window.location.href.split('/gonghui')[0]}},methods:{parameterDeal(_parameter){var _sender="";if(_parameter instanceof Object){for(var k in _parameter){_sender+=k+"="+_parameter[k]+"&";}return _sender.replace(/\&$/g,"");}else{return _parameter;}},createXMLHttpRequest(){try{return new window.XMLHttpRequest();}catch(e){try{return new ActiveXObject("MSXML2.XMLHTTP.6.0");}catch(e){try{return new ActiveXObject("MSXML2.XMLHTTP.3.0");}catch(e){try{return new ActiveXObject("MSXML2.XMLHTTP");}catch(e){try{return new ActiveXObject("Microsoft.XMLHTTP");}catch(e){throw new Error("该浏览器版本太低,已经被大部分市场淘汰,请升级!!!");return;}}}}}},$ajax(_method,_url,_async,_parameter,_callBack){_url=this.Host+_url;var that=this;var _ajax=this.createXMLHttpRequest();if(_ajax){_ajax.open(_method,_url,_async);_ajax.onreadystatechange=function(){if(_ajax.readyState==4 && _ajax.status==200){_callBack(JSON.parse(_ajax.responseText));}else{// console.log(_ajax.readyState);}}_ajax.setRequestHeader("content-type","application/x-www-form-urlencoded;charset=utf-8");try {_ajax.send(that.parameterDeal(_parameter));} catch (e) {return false;} finally {return false;}}}}
})
在组件里面使用this.$ajax;this.Host即可使用;
这篇关于Vue解析一之挂载全局变量与方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!