@Triplicate

Как получить id по текущему счёту и передать в запрос Pinia store?

Я использую Vue3 Composition Api + Pinia

У меня есть AccountStore:

import { defineStore } from 'pinia'

export interface Account {
    id: string
    number_personal_account: string
    building_type: string
    checked: number
    balance: number
    created_at: string
    house_guid: string
    room_guid: string
}

export type Filters = 'all' | 'processing' | 'debt'

export interface State {
    current: Account | Record<string, string>
    accounts: Account[]
}

export const useAccountStore = defineStore('Account', {
    state: () => {
        return {
            current: {},
            accounts: [],
        } as State
    },
    getters: {},
    actions: {
        initStore(payload: Account[]) {
            this.$patch({
                current: payload.length ? payload[0] : {},
                accounts: payload,
            })
        },
    },
})


Асинхронный компонент TheCurrentAccount.vue, который инициализирует стор

<template>
    <button class="current-account">
        <icon-accounts-list class="current-account__icon" />
        <p class="current-account__title">
            {{ currentAccount.building_type ?? 'Лицевые счета' }}
        </p>
    </button>
</template>

<script lang="ts">
import { computed, defineComponent } from 'vue'
import AccountService from '../api/AccountService'
import { useAccountStore } from '../store/useAccountStore'
import IconAccountsList from './Icons/IconAccountsList.vue'

export default defineComponent({
    name: 'TheCurrentAccount',
    components: {
        IconAccountsList,
    },
    async setup() {
        const accountStore = useAccountStore()

        const currentAccount = computed(() => {
            return accountStore.current
        })

        const response = await AccountService.getAll()

        const accounts = [
            {
                id: 'f77e3f0c-d9ab-4c7e-a6f6-da298cd64b5e',
                number_personal_account: '1500000002',
                building_type: 'Квартира',
                checked: 1,
                balance: 0,
                created_at: '2021-10-08T13:21:10.000000Z',
                house_guid: '123',
                room_guid: '312',
            },
        ]

        accountStore.initStore(accounts)

        return { currentAccount }
    },
})
</script>

<style lang="scss" scoped>
@forward '@styles/components/TheCurrentAccount.scss';
</style>


И компонент баланса в котором я хочу получить текущий счет из стора, взять его id и передать как аргумент к запросу.
Если я передаю в разметку currentAccountId, то id отобразиться, но мне его нужно получить на момент отправки запроса.
Пробовал через watch, computed, выносил логику в store - мимо. Понимаю, что на момент инициализации компонента, у меня еще стор не обновился, как это сделать корректнее, объясните пожалуйста

<template>
    <button class="balance">
        <p>{{ orderLink }}</p>
    </button>
</template>

<script lang="ts">
import { computed, defineComponent } from 'vue'
import AcquiringService from '../api/AcquiringService'
import { useAccountStore } from '../store/useAccountStore'

export default defineComponent({
    name: 'TheBalanceCard',
    async setup() {
        const accountStore = useAccountStore()

        const currentAccountId = computed(() => {
            return accountStore.current.id
        })

        const orderLink = await AcquiringService.getOrderLink(
            currentAccountId.value
        )

        return { orderLink }
    },
})
</script>

<style lang="scss" scoped>
@forward '@styles/components/TheBalanceCard.scss';
</style>
  • Вопрос задан
  • 99 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы