vue项目 html标签中能否直接使用外部引入的js方法

今天项目迭代的时候,发现一个问题。

因为后端返回的更新时间这个字段是时间戳,想着用到的地方会挺多的,就直接封装了一个公共方法出去。

时间戳转时间格式为年-月-日 时:分:秒

    // 秒转2021-03-05 12:11:30
    export const transFormTime = (timestamp) => {
        if (timestamp) {
            const time = new Date(timestamp);
            const Y = time.getFullYear();
            const M = time.getMonth() + 1 < 10 ? '0' + (time.getMonth() + 1) : time.getMonth() + 1;
            const D = time.getDate() < 10 ? '0' + time.getDate() : time.getDate();
            const h = time.getHours() < 10 ? '0' + time.getHours() : time.getHours();
            const m = time.getMinutes() < 10 ? '0' + time.getMinutes() : time.getMinutes();
            const s = time.getSeconds() < 10 ? '0' + time.getSeconds() : time.getSeconds();
            return `${Y}-${M}-${D} ${h}:${m}:${s}`;
        } else {
            return '';
        }
    };
复制代码

在需要时间转换的页面引入该方法,如下:

截屏2021-06-22 下午1.35.23.png

在需要转换的位置使用该方法,如下:

截屏2021-06-22 下午1.50.13.png

结果居然会报错,找不到transFormTime方法

截屏2021-06-22 下午1.41.16.png

然后根据以往的经验检查了引入的路径,方法名都确定没有问题。然后我试着在页面初始化的时候调用这个方法,发现没有报错,可以返回预期的结果。说明只是在html中不能直接使用js引入的方法。

最后尝试在methods中重写一个方法,在该方法中调用js引入的transFormTime方法,在html中调用该方法,发现是生效的。

截屏2021-06-22 下午1.54.22.png

通过百度找到一个解释,说的挺好的,也放链接在这儿:原链接

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享