首页 > 解决方案 > 初始化松树状态

问题描述

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

一点背景:用户登陆表单的第一页;表单调用 (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>

第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
        }
    }
})

标签: vue.jsnuxt.jsvuex

解决方案


推荐阅读