在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',存入字符串,天数) //存cookie
this.$common.getCookie('cookieName') //取
this.$common.delCookie('cookieName') //删除
转载:https://blog.csdn.net/YourNikee/article/details/102476649
查看评论