简体   繁体   English

状态Vuex无法与Nuxt.js一起正常工作

[英]State Vuex don't work correctly with Nuxt.js Problem

I'm trying to set state vuex on my Nuxt.js App, but it don't work correctly. 我正在尝试在Nuxt.js应用程序上设置状态vuex,但是它无法正常工作。 So here i'm set my state with fetch method: 所以在这里,我用获取方法设置状态:

fetch({app, store, route}) {
    app.$axios.$get(`apps/${route.params.id}`)
      .then(res => {
        store.dispatch('setApp', {
          ...res,
          id: route.params.id
        })
        console.log(app.store.state.app);
      })
  }

Here everything works correcty when i'm logging app.store, data is there, but when i'm trying to log it in: 当我登录app.store时,这里的所有数据都可以正确运行,但是数据在那里,但是当我尝试登录时:

  created() {
    console.log(this.$store);
  },
  mounted() {
    console.log(this.$store);
  }

Here's my store code: 这是我的商店代码:

const store = () => new Vuex.Store({

  state: {
    app: ''
  },
  mutations: {
    'SET_APP' (state, payload) {
      state.app = payload
    }
  },
  actions: {
    setApp (ctx, payload) {
      ctx.commit('SET_APP', payload)
    }
  },
  getters: {

  }
})

i't don't work my state is empty so data is not render on my template ( I hope that somebody gotta help me ! 我不工作,我的状态是空的,所以数据没有呈现在我的模板上(我希望有人能帮助我!

PS: Also when it's logging on client-side everything works fine, but in SSR not ( PS:同样,当它在客户端登录时,一切正常,但是在SSR中,不(

As stated from the docs 文档所述

To make the fetch method asynchronous, return a Promise, Nuxt.js will wait for the promise to be resolved before rendering the component. 为了使fetch方法异步,返回Promise,Nuxt.js将在渲染组件之前等待Promise被解决。

In code example above, axios request is made inside fetch hook, but Nuxt will not wait for it to resolve, as no promise is returned, so it keeps rendering the component, thus running created and mounted hooks, which by the time of invocation do not have filled $store . 在上面的代码示例中,axios请求是在fetch挂钩中发出的,但是Nuxt不会等待它解决,因为没有返回承诺,因此它会继续渲染该组件,从而运行已created和已mounted挂钩,在调用时会执行此操作还没有填满$store

In order to make it work, you should return a promise from fetch method. 为了使其工作,您应该从fetch方法返回一个promise。

If no additional code is present in your app, simply adding return statement will solve the issue: 如果您的应用程序中没有其他代码,只需添加return语句即可解决此问题:

fetch({app, store, route}) {
  return app.$axios.$get(`apps/${route.params.id}`)
    .then(res => {
      store.dispatch('setApp', {
      ...res,
      id: route.params.id
    })
    console.log(app.store.state.app);
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM