【问题标题】:set data only on first load with nuxt.js仅在使用 nuxt.js 首次加载时设置数据
【发布时间】:2018-10-24 11:52:40
【问题描述】:

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

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

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

我尝试在index.js 中使用nuxtServerInit 操作设置数据:

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)

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

【问题讨论】:

  • 您是否尝试过将 fetch 放入显示帖子组件的 createdmounted 生命周期挂钩中?
  • 好的问题是,如果我使用 NuxtServerInit,那里调度的动作必须返回一个承诺,所以必须以'return'开头:返回 axios.get() 而不仅仅是 axios.get ()

标签: javascript vue.js vuejs2 nuxt.js


【解决方案1】:

没有开箱即用的解决方案,因为它特定于您的要求/需要。我的解决方案与您的解决方案非常相似,但我没有检查数据数组的大小,而是在每个商店模块中引入了附加变量 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
    }
}

【讨论】:

    猜你喜欢
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    相关资源
    最近更新 更多