前端開發的時候,總會需要寫一些js函數,在vue框架中為了方便使用,可以考慮注冊一個全局的js函數,下面是注冊步驟:
1.0 可以在assets文件中的js文件下面新建一個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 下面將yun.js文件注冊到vue的全局中去,需要在main.js文件下面注冊全局:如圖下
4.0 前面步驟將自定義的js注冊到全局去了,后面就可以使用了,如下:
以上就是在vue中注冊全局的自定義js文件的步驟,以后需要添加js函數,就在yun.js加上去就可以調用了