无法使用 Vue 选项 API 设置基本的 Pinia 商店

问题描述 投票:0回答:2

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

在我的应用程序中,我有:

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

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

import {defineStore} from 'pinia';

export const useTestPiniaStore = defineStore('testStore', {
    state: () => {
        return {
            name: 'bob'
        }
    },
})

在我的 vue 组件中,我有:

<template>
    <div class="menu-page">
        <h1>{{name}}</h1>
    </div>
</template>
<script>
import { mapState } from 'pinia';
import useTestPiniaStore from '@store/modules/piniaStore';

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

Pinia 出现在我的 Vue 开发工具中,但其中没有商店出现,我收到错误

Cannot read properties of undefined (reading 'name')

我不明白我在这里做错了什么。如果有人能提出一些建议,我们将不胜感激。

javascript vue.js vuex pinia
2个回答
0
投票

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

第一个参数应该是

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

你的计算道具应该是这样的:

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

export default {
  computed: {
    ...mapState(useTestPiniaStore, ['name']), 👈
  },
}
</script>

演示


0
投票

在尝试使用 Options API 通过 Pinia 和 Vue 设置 mapState 时,我也没有运气。

对我有用的是使用 mapStores。这是cookbook中的一个例子:

import { mapStores } from 'pinia'

// given two stores with the following ids
const useUserStore = defineStore('user', {
  // ...
})
const useCartStore = defineStore('cart', {
  // ...
})

export default {
  computed: {
    // note we are not passing an array, just one store after the other
    // each store will be accessible as its id + 'Store'
    ...mapStores(useCartStore, useUserStore)
  },

  methods: {
    async buyStuff() {
      // use them anywhere!
      if (this.userStore.isAuthenticated()) {
        await this.cartStore.buy()
        this.$router.push('/purchased')
      }
    },
  },
}
© www.soinside.com 2019 - 2024. All rights reserved.