使用 Vue 选项 API 设置基本 Pinia 商店时遇到问题

bjo*_*and 5 javascript vue.js vuex pinia

我是 Pinia 的新手,在建立一家基本商店时遇到困难。我一直在关注 Pinia 自己的文档,但似乎无法从我映射到 Pinia 商店的 vue 组件中读取任何状态。

在我的应用程序中我有:

import { createPinia } from 'pinia';
export default function initApp(el) {
    let app = createApp(MenuApp);
    app.use(router).use(createPinia()).mount(el);
}
Run Code Online (Sandbox Code Playgroud)

我建立了一个超级基本的 Pinia 商店,只是为了开始:

import {defineStore} from 'pinia';

export const useTestPiniaStore = defineStore('testStore', {
    state: () => {
        return {
            name: 'bob'
        }
    },
})
Run Code Online (Sandbox Code Playgroud)

在我的 vue 组件中,我有:

import { createPinia } from 'pinia';
export default function initApp(el) {
    let app = createApp(MenuApp);
    app.use(router).use(createPinia()).mount(el);
}
Run Code Online (Sandbox Code Playgroud)

Pinia 出现在我的 Vue 开发工具中,但其中没有出现商店,并且出现错误 Cannot read properties of undefined (reading 'name')

我不明白我在这里做错了什么。如果有人可以给出一些指示,我们将不胜感激。

ton*_*y19 2

mapState()需要两个参数,但您只传递了一个。

第一个参数应该是useTestPiniaStore,第二个参数应该是要映射的状态属性数组(或对象)。看来您正在尝试引用nameuseTestPiniaStore这将是undefined.

您计算出的 prop 应该如下所示:

<script>
import { mapState } from 'pinia'
import { useTestPiniaStore } from '@/store'

export default {
  computed: {
    ...mapState(useTestPiniaStore, ['name']), 
  },
}
</script>
Run Code Online (Sandbox Code Playgroud)

演示

  • 谢谢,但现在我不断收到“无法读取未定义的属性(读取'$id')”..我也将mapStores添加到我的组件中。 (2认同)