javascript - Vue 3 Composition API 提供/注入(inject)在单个文件组件中不起作用

标签 javascript vue.js vue-component vuejs3 vue-composition-api

我正在使用 Composition API 在 VueJS 3 中创建一个库。我实现了 docs 中提到的提供/注入(inject).但子组件中的属性仍未定义,我在浏览器控制台中收到以下错误:
Console Output
我的代码的一个非常简单的实现如下:

Usage In Project

<ThemeProvider>
    <Button color="green">
        ABC
    </Button>
</ThemeProvider>

<script>
    import { ThemeProvider, Button } from 'my-library'

    export default {
        name: 'SomePage',
        setup() {...},
    }
</script>

ThemeProvider.js (Parent Componen)

import { toRefs, reactive, provide, h } from 'vue'

export default {
    name: 'theme-provider',
    props:
        theme: {
            type: Object,
            default: () => ({...}),
        },
    },
    setup(props, { slots }) {
        const { theme } = toRefs(props)

        provide('theme', reactive(theme.value))

        return () =>
            h(
                'div',
                {...},
                slots.default()
            )
    },
}

Button.js (Child Component)

import { inject, h } from 'vue'

export default {
    name: 'Button',
    setup(props, { slots }) {
        const theme = inject('theme')
        console.log(theme)  // returns undefined

        return () =>
            h(
                'button',
                {...},
                slots.default()
            )
    },
}

最佳答案

我在使用 async setup() 时遇到了同样的警告和问题

inject() can only be used inside setup() or functional components.


问题是在初始化注入(inject)之前有一个异步调用,我不确定它为什么重要。
解决方案是在调用异步函数之前声明注入(inject)。

import getCharacters from "../composables/characters";
import { inject } from "vue";
export default {
  async setup() {
    const store = inject("store");
    const { characters } = await getCharacters();
    
    store.updateChars(characters)

    return {
      characters,
      store
    };
  },
};


关于javascript - Vue 3 Composition API 提供/注入(inject)在单个文件组件中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63107387/

相关文章:

javascript - 如何使用 fs 从 json 文件中获取 ID

vue.js - Vue 框架中的十进制格式

typescript - 为 TypeScript 使用 @Prop 装饰器 - 编译器给出错误要求初始化 prop

javascript - Promise.resolve 没有传入任何参数

javascript - 为什么没有主流的 JavaScript 专业认证?

javascript - Vue.js - 更新路由器 View

javascript - 如何在递归组件中出现 "Avoid mutating a prop directly"

javascript - 如何将对象传递给 VueJS 中的 Prop 值

Javascript 变量保持未定义状态

vue.js - vue/cli中router中的base参数有什么用?