自己新建一个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()