Nuxt 读取组件内部的模块状态

Nuxt read module state inside a component

我有一个 Nuxt 应用程序,其 store 目录类似于此文件夹 https://nuxtjs.org/docs/2.x/directory-structure/store#example-folder-structure.

假设我在 cart 文件夹中的模块状态中有一个 属性 isComplete

我收到以下错误 Property 'shop' does not exist on type 'RootState'.

如何在 Vue 组件中访问此 属性?

Component.vue

<script lang="ts">
import { defineComponent, onMounted } from '@nuxtjs/composition-api'
import { useStore } from '~/store'

export default defineComponent({
  name: 'Component',
  setup() {
    const store = useStore()

    onMounted(() => {
      if (store.state.shop.cart.isComplete) {
        // Execute some code
      }
    })
  },
})
</script>

我的store/index.ts有以下实现

import { InjectionKey, useStore as baseUseStore } from '@nuxtjs/composition-api'

export interface RootState {}

export const state = () => ({})

export const injectionKey: InjectionKey<RootState> =
  Symbol('vuex-injection-key')

export const useStore = () => {
  return baseUseStore(injectionKey)
}

store/shop/cart/state.ts

export interface CartState {
  isComplete: boolean
}

export const state = (): CartState => ({
  isComplete: false,
})

商店状态

名为 state 的存储文件应该有一个对象返回方法作为其默认导出,因此 store/shop/cart/state.ts 应该包含 export default state(其中 state 是方法)作为它的最后一行。否则,您将在浏览器控制台中看到一条警告:

store/shop/cart/state.ts should export a method that returns an object

或者您可以将 store/shop/cart/state.ts 重命名为 store/shop/cart/index.ts(也许是基于导出的 state 常量的初衷)。

RootState类型

此处没有可用的类型推断,因此 RootState 需要显式键入以包含模块的状态。

  1. 从命名空间模块导入 CartState

  2. 添加一个以每个命名空间模块命名的键,根据需要嵌套(即 shop,然后是 cart)。为 cart 键应用 CartState 类型。

// store/index.ts
import type { CartState } from './shop/cart' 1️⃣

export interface RootState {
  shop: {
    cart: CartState, 2️⃣
  }
}

GitHub demo