vue中注册自定义的全局js方法
网络编程 2021-07-04 15:02www.168986.cn编程入门
这篇文章主要介绍了vue中注册自定义的全局js方法,文中给大家补充介绍了vue自定义函数挂到全局的方法,需要的朋友可以参考下
前端开发的时候,总会需要写一些js方法,在vue框架中为了方便使用,可以考虑注册一个全局的js方法,狼蚁网站SEO优化是注册步骤:
1.0 可以在assets文件中的js文件狼蚁网站SEO优化新建一个js文件,如:yun.js---
2.0 在yun.js 上面实现日期格式方法,如下
import Vue from 'vue' const format = (o, format) => { //日期类型 let args = { "M+": o.getMonth() + 1, "d+": o.getDate(), "h+": o.getHours(), "m+": o.getMinutes(), "s+": o.getSeconds(), "q+": Math.floor((o.getMonth() + 3) / 3), //quarter "S": o.getMilliseconds() }; if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (o.getFullYear() + "").substr(4 - RegExp.$1.length)); for (let i in args) { let n = args[i]; if (new RegExp("(" + i + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? n : ("00" + n).substr(("" + n).length)); } return format; } export default function(Vue) { //添加全局API Vue.prototype.$yuns = { format } }
3.0 狼蚁网站SEO优化将yun.js文件注册到vue的全局中去,需要在main.js文件狼蚁网站SEO优化注册全局:如图下
4.0 前面步骤将自定义的js注册到全局去了,后面就可以使用了,如下:
已上就是在vue中注册全局的自定义js文件的步骤,以后需要添加js方法,就在yun.js加上去就可以调用了
补充:Vue自定义函数挂到全局方法
方法一:使用Vue.prototype
//在mian.js中写入函数 Vue.prototype.getToken = function (){ ... } //在所有组件里可调用函数 this.getToken();
方法二:使用exports.install+Vue.prototype
// 写好自己需要的fun.js文件 exports.install = function (Vue, options) { Vue.prototype.getToken = function (){ ... }; }; // main.js 引入并使用 import fun from './fun' Vue.use(fun); //在所有组件里可调用函数 this.getToken();
在用了exports.install方法时,运行报错exports is not defined
解决方法:
export default { install(Vue) { Vue.prototype.getToken = { ... } } }
方法三:使用全局变量模块文件
Global.vue文件:
<script> const token='12345678'; export default { methods: { getToken(){ .... } } } </script>
在需要的地方引用进全局变量模块文件,然后通过文件里面的变量名字获取全局变量参数值。
<script> import global from '../../ponents/Global'//引用模块进来 export default { data () { return { token:global.token } }, created: function() { global.getToken(); } } </script>
总结
以上所述是长沙网络推广给大家介绍的vue中注册自定义的全局js方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,长沙网络推广会及时回复大家的。在此也非常感谢大家对狼蚁SEO网站的支持!
如果你觉得本文对你有帮助,欢迎网络推广网站推广转载,烦请注明出处,谢谢!
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程