【问题标题】:Nuxt read module state inside a componentNuxt 读取组件内的模块状态
【发布时间】:2021-10-13 08:58:38
【问题描述】:

我有一个 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,
})

【问题讨论】:

    标签: javascript typescript vue.js nuxt.js vuex


    【解决方案1】:

    存储状态

    名为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

    【讨论】:

    • 非常感谢!根据需要工作!但是,我创建了一个 store/shop/cart/mutations.ts,并将其导入到 store.shop/cart/state.ts 中。这个mutations.ts 导出一个包含每个突变方法的mutations 对象。但是,我收到错误[vuex] unknown mutation type: MY_MUTATION。导出的对象的类型为MutationTree&lt;CartState&gt;。我必须在store/index.ts 中导入模块突变吗?
    • 我检查了store,似乎导出突变名称是错误的:) store/cart/MY_MUTATION 而不是MY_MUTATION
    猜你喜欢
    • 2019-09-22
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 2018-10-10
    • 2019-12-15
    • 1970-01-01
    相关资源
    最近更新 更多