source

Init pinia 상태

goodcode 2022. 8. 24. 23:54
반응형

Init pinia 상태

pinia를 사용하여 앱 상태를 관리합니다.제목에 기재되어 있는 것처럼 NuxtServerInit 훅 아날로그 pinia를 찾고 있습니다.

간단한 컨텍스트:사용자는 폼의 첫 번째 페이지에 도착합니다.Form calls (f.e.) state.getCountries()는 선택한 입력 중 하나에 대한 항목 목록을 가져옵니다.사용자는 국가를 선택하고 두 번째 페이지로 이동합니다.두 번째 페이지에도 액세스 할 필요가 있습니다.사용자가 첫 번째 페이지에서 두 번째 페이지로 이동하면 OK입니다.그러나 국가 목록은 비어 있습니다(명확한 사용자).s 두 번째 페이지

마음에 드는 ATMif (state.countries.length === 0) state.getCountries()

하지만 좋은 방법은 아닌 것 같아요

1 페이지

<template>
   <app-select :items="send.countries" />
</template>

<script>
import { defineComponent } from '@nuxtjs/composition-api'
import { useSend } from '~/store/send'

export default defineComponent({
    setup() {
       const send = useSend()

       send.getCountries()

       return { send }
    }
}
</script>

2 페이지

<template>
   <app-select :items="send.countries" />
</template>

<script>
import { defineComponent } from '@nuxtjs/composition-api'
import { useSend } from '~/store/send'

export default defineComponent({
    setup() {
       const send = useSend()
       // if User refreshed Second page, countries is empty list
       if (send.countries.length === 0) {
           send.getCountries()
       }

       return { send }
    }
}
</script>

store/send.ts

import { defineStore } from 'pinia'

export const useSend = defineStore({
    state: () => {
        return {
            countries: []
        }
    },

    actions: {
        getCountries() {
            const res = this.$nuxt.$api.countries.get()
            this.countries = res.data
        }
    }
})

언급URL : https://stackoverflow.com/questions/68803829/init-pinia-state

반응형