vue注册全局js方法(让浏览器兼容ES6语法)

自己新建一个js文件如test.js

// 这里写全局的ES6语法(ES2015)如果在index.html写个别浏览器不兼容
const publicFunction = {
    // 睡眠
    sleep(d) {
        return new Promise((resolve) => setTimeout(resolve, d))
    }
    // 你也可以定义多个
    xxxxx(a, b, c) {
        retrun a, b, c
    }
}
export default {
    install(vue) {
        if (!vue.$publicFunction) {
            vue.$publicFunction = publicFunction
        }
        vue.mixin({
            created: function() {
                this.$publicFunction = vue.$publicFunction
            }
        })
    }
}

然后去到main.js

import publicFunction  from 'xxxx/xxxx/test.js'

Vue.use(publicFunction)

然后来到vue文件调用

this.$publicFunction.sleep(1800)

你写了多个方法你想调用其中的一个就 this.$publicFunction.xxxx()

发布了185 篇原创文章 · 获赞 121 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/echo_Ae/article/details/81077774
今日推荐