【问题标题】:VueJS - Created global service function with vue provide , get undefined when call the service in vue componentVueJS - 使用 vue 提供创建全局服务功能,在 vue 组件中调用服务时未定义
【发布时间】: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


    【解决方案1】:

    provide 没有inject 是没用的

    如果您不想使用inject,只需使用app.config.globalProperties(在Vue 2 中替换Vue.prototype

    app.config.globalProperties.$service = createRepository({httpClient})

    this.$service 现在可以在应用程序的每个组件中使用...

    【讨论】:

    • 谢谢。我按照你的方式尝试,它只是添加 globalProperties 就可以了,不需要创建 ServiceProvider。如果没有 serviceProvider,您能否简要介绍一下,仅使用 app.config.globalProperties 有什么不同?
    • 坦率地说,真的很难理解你的意思。而且我看不到整个 serviceProvider.... 除了可能将 $service 键传播到多个 Vue 实例属性
    • 实际上我正在尝试控制调用 API 的服务,但仍然不确定哪个实现是最好的。
    • “最佳”取决于很多事情。使用app.config.globalProperties 是最简单的方法。如果您打算使用Composition API,则使用提供/注入可能是最好的,因为thissetup() 函数中不可用...
    猜你喜欢
    • 2016-09-13
    • 2020-02-23
    • 2021-08-05
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 2018-12-02
    • 2021-03-24
    相关资源
    最近更新 更多