定义公用方法"/>
Vue定义公用方法
在src目录下新建common公用方法文件夹用于存放公用方法列表
common下新建common.js
该示例定义存、取、删cookie方法
main.js中引入该文件,并将其添加到Vue原型链上
import common from './common/common'Vue.prototype.$common = common //其中$common就是调用时所使用的方法
紧接着定义common.js中的方法,录入即用
export default { //公开/*** 设置cookie**/setCookie(name, value, day) {let date = new Date();date.setDate(date.getDate() + day);document.cookie = name + '=' + value + ';expires=' + date;},/*** 获取cookie**/getCookie(name){let reg = RegExp(name + '=([^;]+)');let arr = document.cookie.match(reg);if (arr) {return arr[1];} else {return '';}},/*** 删除cookie**/delCookie(name) {setCookie(name, null, -1);}
}
使用:
在需求页面打印 this.$common
打印结果是这样的就说明方法添加成功了,如果想要添加其他的方法也可以通过这样的形式在原型链上新增方法
要使用则是:
this.$common.setCookie('cookieName',存入字符串,天数) //存cookiethis.$common.getCookie('cookieName') //取this.$common.delCookie('cookieName') //删除
更新:
若是想将其直接定义为全局,且在this指向下,可以这样做:
首先依旧是定义你想要作为公用的方法
/*** 设置cookie**/
function setCookie(name, value, day) {let date = new Date();date.setDate(date.getDate() + day);document.cookie = name + '=' + value + ';expires=' + date;
};/*** 获取cookie**/
function getCookie(name) {let reg = RegExp(name + '=([^;]+)');let arr = document.cookie.match(reg);if (arr) {return arr[1];} else {return '';}
};/*** 删除cookie**/
function delCookie(name) {setCookie(name, null, -1);
};
然后:
将方法注册,并添加到Vue的原型链
export default {install(Vue,opeions){Vue.prototype.getCookie = getCookie;Vue.prototype.setCookie = setCookie;Vue.prototype.delCookie = delCookie;}
};
注:注册之后需要在main.js
引入并use
才能生效
import commonApi from './util/common' //你的公用方法文件路径
Vue.use(commonApi)
over
更多推荐
Vue定义公用方法
发布评论