javascript - 仅在首次加载时使用 nuxt.js 设置数据

标签 javascript vue.js vuejs2 nuxt.js

我是 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')
       
        
      }
}

但不起作用:操作已分派(dispatch)(在服务器上)但未设置数据。

所以我试过 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) 上运行

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

最佳答案

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

您还可以像这样简化您的获取方法:

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

关于javascript - 仅在首次加载时使用 nuxt.js 设置数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50336775/

相关文章:

node.js - 为 vue-cli 运行 "npm run dev"时出现跨环境问题

javascript - 如何在没有 WebPack 构建过程的情况下在 HTML 页面中使用 VueJS .vue 组件?

vuejs2 - VueJs : Pass Dynamic Components as props to another Component and render them

javascript - GSAP:在制作 SVG 动画时保留以前的转换

javascript - 使用 JQuery 为我的图像添加动画

jQuery 上的 JavaScript 创建的代码永远不会被调用

javascript - 为什么在声明子 namespace 时不能使用 var?

javascript - 无法更改 Vue 实例数据值

javascript - 在vue中使用checkbox作为数据绑定(bind)

javascript - VueJS 酒店日期选择器 : issue in getting selected date via event listener