vue之注册自定义的全局js方法

时间:2019-11-15
本文章向大家介绍vue之注册自定义的全局js方法,主要包括vue之注册自定义的全局js方法使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

前端开发的时候,总会需要写一些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加上去就可以调用了

原文地址:https://www.cnblogs.com/guhonghao/p/11866665.html