【问题标题】:Vue 3 - inject() can only be used inside setup or functional componentsVue 3 - inject() 只能在设置或功能组件中使用
【发布时间】:2021-03-28 03:29:42
【问题描述】:

我不明白为什么会出现此错误。我正在尝试在组合函数中使用 Vuex 存储,但它不断向我抛出有关注入的错误(我什至没有使用注入)。我的应用程序对后端进行 await api 调用,如果有错误调用我的组合函数。

[Vue warn]: inject() can only be used inside setup() or functional components.
inject    @ runtime-dom.esm-bundler-9db29fbd.js:6611
useStore  @ vuex.esm-bundler.js:13
useErrorHandling @  useErrorHandling.js:5
checkUserExists  @  auth.js:53

这是我的合成函数

import { useStore } from 'vuex'

function useErrorHandling()
{
    const store = useStore()  // <-- this line

    function showError(errorMessage) {
        console.log(errorMessage)
    }

    return { showError }
}

export default useErrorHandling

如果我删除此行,则不会引发该错误

// const store = useStore()  // <-- this line

更新:这是函数的调用方式。

/**
     * Check if a user exists in database
     */
    static async checkUserExists(data)
    {
        const { env } = useEnv()
        const { jsonHeaders } = useHTTP()
        const { showError } = useErrorHandling()
        
        try {
            let response = await fetch(`${env('VITE_SERVER_URL')}/auth/check-user-exists`, {
                method: 'POST',
                body: JSON.stringify(data),
                headers: jsonHeaders,
            })

            if (!response.ok) {
                let errorMessage = {
                    statusText: response.statusText,
                    statusCode: response.status,
                    body: '',
                    url: response.url,
                    clientAPI: 'api/auth.js @ checkUserExists',
                }
                
                const text = await response.text()
                errorMessage.body = text

                showError(errorMessage) // <-- here
                return
            }

            response =  await response.json()
            return response.user_exists
        } catch (error) {
            alert('Error occured!')
            console.log(error)
        }
    }

【问题讨论】:

  • 你能显示你在哪里使用这个文件的代码吗?
  • 这不是 setup(){} 您不能在 setup() 之外使用 const store = useStore()'。
  • @laurisstepanovs 那么如何在合成函数中使用存储?
  • 您可以像在文件中那样使用它。

标签: javascript vue.js vuex vuejs3 vue-composition-api


【解决方案1】:

错误告诉您useStore 用于组合 API。来自docs

要在设置挂钩中访问存储,您可以调用 useStore 函数。这相当于使用 Option API 在组件中检索 this.$store。

要在模块中使用store,您可以在创建它的模块中import { store }

store.js

export const store = createStore({
...
})

其他模块

import { store } from './store'

【讨论】:

    猜你喜欢
    • 2021-01-21
    • 1970-01-01
    • 2020-09-07
    • 2019-01-27
    • 2017-05-22
    • 2021-09-26
    • 2021-07-20
    • 1970-01-01
    • 2020-01-25
    相关资源
    最近更新 更多