【发布时间】:2021-07-03 05:42:27
【问题描述】:
我创建了一个 vue 基础项目。
我想做什么:
- 创建一个全局服务函数(用于调用 API),在每个能够使用
this.$service.service.get()调用我想要的任何 API 的组件中,无需注入。 - 使用 app.provide 并将服务声明为全局常量
- 这是我的 main.js
// main.js
const config = {
service: createRepository({httpClient})
}
// Vue.prototype.$repository = config.repository;
const app = createApp({
created() {
},
render: () => (
h(App)
)
});
app.provide('$service', config.service)
app.mixin(mixin)
app.use(router)
app.mount('#app');
// mixin.js
import serviceProvider from "./serviceProvider";
const mixins = [serviceProvider];
const mixin = {
install: function (Vue, options) {
mixins.forEach(m => Vue.mixin(m))
}
}
export default mixin;
//serviceProvider.js
export default {
beforeCreate() {
const options = this.$options;
const service = options.$service || (options.parent ? options.parent.$service : null);
if (!service) return;
this.$service = service;
Object.keys(service).forEach((key, index) => {
this[`$${key}`] = service[key]
})
}
}
我的预期结果是什么:
- 期望看到从 HomePage.vue 调用的函数
// HomePage.vue
async created(){
await this.$service.authService.get()
}
我目前的结果是什么:
- authService 未定义
请告知我当前的设置有任何问题。谢谢。
【问题讨论】:
标签: javascript vue.js vuejs3