初始状态

Eug*_*run 12 vue.js vuex nuxt.js

我们使用pinia来管理应用程序状态。正如标题中提到的,我正在寻找 pinia 的 NuxtServerInit 钩子类似物。

一些背景信息:用户登陆表单的第一页;Form 调用 (fe) state.getCountries() 来获取选择输入之一的项目列表;用户选择一个国家/地区并导航到第二页,该页面还必须有权访问国家/地区列表;可以,当用户从第一页转到第二页时;但是如果用户刷新第二页,国家列表是空的(很明显);

我很喜欢自动取款机if (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>
Run Code Online (Sandbox Code Playgroud)

第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>
Run Code Online (Sandbox Code Playgroud)

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
        }
    }
})
Run Code Online (Sandbox Code Playgroud)