首页 > 解决方案 > 仅在使用 nuxt.js 首次加载时设置数据

问题描述

我是 nuxt.js 的新手,所以我想知道通过 REST api 设置一些数据的最佳方法是什么。

我有一个这样的商店文件夹:

store
    -posts.js
    -categories.js
    -index.js

我尝试使用以下nuxtServerInit操作设置数据index.js

export const actions = {
    async nuxtServerInit({ dispatch }) {
        await dispatch('categories/setCategories')
        await dispatch('posts/loadPosts','all')
       
        
      }
}

但不起作用:(在服务器上)调度操作但未设置数据。

所以我尝试了fetch但每次加载我必须显示帖子的页面时都会调用此方法。即使在总体布局中,我这样做:

<template>
  <div>
    <Header />
    <keep-alive>
      <nuxt/>
    </keep-alive>
    
  </div>
</template>

所以我的解决方案,现在,是以这种方式使用 fetch ,在页面组件中:

 async fetch({store}){
       if(store.getters['posts/getPosts'].length === 0 && store.getters['categories/getCategories'].length === 0 ){
            await store.dispatch('categories/setCategories')
            await store.dispatch('posts/loadPosts','all')
       } 
   }

另外,我注意到的一件事是 fetch 似乎不适用于根页面组件(pages/index.vue)

我的解决方案似乎有效,但也许还有另一种更好的方法来设置数据?

标签: javascriptvue.jsvuejs2nuxt.js

解决方案


没有开箱即用的解决方案,因为它特定于您的要求/需求。我的解决方案与您的解决方案非常相似,但我没有检查数据数组的大小,而是loaded在每个商店模块中引入了额外的变量。如果加载为假,我只会获取数据。这种方法更适合具有用户生成内容并需要身份验证的应用程序。它将与 SSR 和客户端一起以最佳方式工作,并且如果用户没有数据,它不会尝试在每次页面访问时获取数据。

您还可以像这样简化 fetch 方法:

async fetch()
{
    await this.$store.dispatch('posts/getOnce')
}

现在您的 posts.js 存储模块将如下所示:

export const state = () => ({
    list: [],
    loaded: false
})

export const actions = {
    async getOnce({ dispatch, state }) {
        if (!state.loaded) {
            dispatch('posts/get')
        }
    },
    async get({ commit, state }) {
        await this.$axios.get(`/posts`)
            .then((res) => {
                if (res.status === 200) {
                    commit('set', res.data.posts)
                }
            })
    }         
}

export const mutations = {
    set(state, posts) {
        state.list = posts
        state.loaded = true
    }
}

推荐阅读