useStore() 方法总是导致组件内的未定义值

useStore() method always leading to undefined value within components

我正在使用 Vue3/Vuex 4/TypeScript。

我正在尝试从我的组件 (App.vue) 中访问我的类型存储。

每当我设置 const store = useStore() 时,store 将始终 return 为 undefined

据我所知,我已经完全按照官方 Vuex 4 TypeScript Support Documentation 进行了逐字记录。

app.ts

import { createApp, Component } from "vue"
import { createWebHistory, createRouter } from "vue-router"
import { store, key } from "./store/store"
import App from "./pages/App.vue"
import Home from "./pages/Home.vue"
import Lookup from "./pages/Lookup.vue"

const About = { template: "<div>About</div>" }

const routes = [
  { path: "/", name: "home", component: Home as Component },
  { path: "/about", name: "about", component: About },
  { path: "/lookup", name: "lookup", component: Lookup as Component },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

createApp(App).use(router, store, key).mount("#app")

export default router

store.ts

import { InjectionKey } from 'vue'
import { createStore, useStore as baseUseStore, Store } from 'vuex'

export interface State {
  count: number
}

export const key: InjectionKey<Store<State>> = Symbol()

export const store = createStore<State>({
  state: {
    count: 0
  }
})

// define your own `useStore` composition function
export function useStore () {
  return baseUseStore(key)
}

App.vue

<script lang="ts">
import { useStore } from '../store/store'
export default {
  setup(): { [key: string]: unknown } {
    const foo = "bar"

    const store = useStore()
    
    console.log(store)
    console.log(store.state.count)

    return { foo }
  },
}
</script>

store 总是 returning 未定义,这是我来自 FireFox 的控制台消息

[Vue warn]: injection "Symbol()" not found. 
  at <App> app.js:5871:17
undefined app.js:16779:13
[Vue warn]: Unhandled error during execution of setup function 
  at <App> app.js:5871:17
Uncaught TypeError: store is undefined
    setup http://boilerplate.local/js/app.js:16780
    callWithErrorHandling http://boilerplate.local/js/app.js:5987
    setupStatefulComponent http://boilerplate.local/js/app.js:12359
    setupComponent http://boilerplate.local/js/app.js:12320
    mountComponent http://boilerplate.local/js/app.js:10027
    processComponent http://boilerplate.local/js/app.js:10003
    patch http://boilerplate.local/js/app.js:9621
    render http://boilerplate.local/js/app.js:10704
    mount http://boilerplate.local/js/app.js:8907
    mount http://boilerplate.local/js/app.js:14290
    <anonymous> http://boilerplate.local/js/app.js:23012
    <anonymous> http://boilerplate.local/js/app.js:23014
    <anonymous> http://boilerplate.local/js/app.js:23016

我一整天都在尝试调试这个问题,但确实无法缩小问题范围。非常感谢任何 help/guidance。

您将 Vuex 实例安装到您的应用程序的语法有点不对。在每次调用 use 时,您只能将一个 Vue 插件安装到应用程序,因此像这样组合 router, store, key 是行不通的。因此,根本没有安装 Vuex。

要修复,请更改此行:

createApp(App).use(router, store, key).mount("#app")

对此:

createApp(App).use(router).use(store, key).mount("#app")

key 只是一个传递给 store 的选项,所以它属于第二次调用。)