服务端渲染 (SSR)
TIP
如果您使用的是
Nuxt.js,您需要阅读这些说明。
使用Pinia创建stores对于SSR来说应该是开箱即用的,只要您在setup函数,getters和actions的顶部调用您的useStore()函数:
export default defineComponent({setup() {// this works because pinia knows what application is running inside of// `setup()`const main = useMainStore()return { main }},})
不在 setup() 中使用 store
如果您需要在其他地方使用store,则需要将传递给应用程序pinia的实例传递给useStore()函数调用:
const pinia = createPinia()const app = createApp(App)app.use(router)app.use(pinia)router.beforeEach((to) => {// ✅ This will work make sure the correct store is used for the// current running appconst main = useMainStore(pinia)if (to.meta.requiresAuth && !main.isLoggedIn) return '/login'})
Pinia方便地将自己作为$Pinia添加到你的应用程序中,因此您可以在像serverPrefetch()这样的函数中使用它:
export default {serverPrefetch() {const store = useStore(this.$pinia)},}
状态激活
为了激活初始状态,您需要确保在HTML的某个地方包含了rootState,以便Pinia以后可以获取它。根据您用于SSR的内容,出于安全原因,您应该转义该状态。我们建议使用Nuxt.js 的 @nuxt/devalue 插件:
import devalue from '@nuxt/devalue'import { createPinia } from 'pinia'// retrieve the rootState server sideconst pinia = createPinia()const app = createApp(App)app.use(router)app.use(pinia)// after rendering the page, the root state is build and can be read directly// on `pinia.state.value`.// serialize, escape (VERY important if the content of the state can be changed// by the user, which is almost always the case), and place it somewhere on// the page, for example, as a global variable.devalue(pinia.state.value)
根据您SSR使用的内容,您将设置一个将在HTML序列化的初始状态变量。您还应该保护自己免受XSS攻击。例如,使用vite-ssr库您就可以使用transformState方法和@nuxt/devalue插件:
import devalue from '@nuxt/devalue'export default viteSSR(App,{routes,transformState(state) {return import.meta.env.SSR ? devalue(state) : state},},({ initialState }) => {// ...if (import.meta.env.SSR) {// this will be stringified and set to window.__INITIAL_STATE__initialState.pinia = pinia.state.value} else {// on the client side, we restore the statepinia.state.value = initialState.pinia}})
您可以根据需要,使用其他替代@nuxt/devalue的方法,例如,如果您可以使用JSON.stringify()/JSON.parse()序列化和解析您的状态,则可以大大提高您的性能。
让这个策略适应您的环境。在客户端调用任何useStore()函数之前,请确保pinia的状态激活。例如,如果我们将状态序列化为一个<script>标签,并使其可以在客户端通过window.__pinia全局访问,我们可以这样写:
const pinia = createPinia()const app = createApp(App)app.use(pinia)// must be set by the userif (isClient) {pinia.state.value = JSON.parse(window.__pinia)}
