介绍
如果你需要让一个工具函数在每个组件可用,可以把方法挂载到 Vue.prototype上。
vue实现代码(获取URL参数, 防抖函数)
创建util.js
export default {
toParams: function(param) { let result = ''; for (let name in param) { if (typeof param[name] != 'function') { if (param[name] === null) { result += '&' + name + '='; } else { result += '&' + name + '=' + encodeURI(param[name]); } } } return result.substring(1); };
debounce: function(fn, wait) { let context = this, args = arguments, timer = null; return function() { context = this; args = arguments; clearTimeout(timer); timer = setTimeout(function() { fn.apply(context, args); }, wait || 250); }; } }
|
全局注册
import util from '..../util.js' Vue.prototype.util = util;
|
全局使用
this.util.toParams(name); this.util.debounce(function, 1000);
|