Vue定义公用方法

编程入门 行业动态 更新时间:2024-10-25 18:25:09

Vue<a href=https://www.elefans.com/category/jswz/34/1771289.html style=定义公用方法"/>

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定义公用方法

本文发布于:2024-03-13 01:49:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1732912.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:定义   方法   Vue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!