vue.js - 初始化松树状态
问题描述
我们使用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
}
}
})
解决方案
推荐阅读
- python - 在类中访问 __attr 时,名称修饰如何工作?
- r - 在R中添加具有重复数的新列
- python - 审查文本中的给定单词
- common-lisp - 在 SBCL 中检查编译器优化
- typescript - Typescript - 来自各种接口列表的数组项
- java - E/AndroidRuntime:致命异常:主进程:com.example.vrtour,PID:14793
- ethereum - 如何监听尚未为单个地址挖掘的传入交易?
- html - 这个冗长的伪类组合是一个有效的陈述吗?
- azure - 使用 Powershell 和 Azure 检索服务总线主题的 AuthoriztionRule 的 ConnectionString
- javascript - javascript过去日期警报