Nuxtjs / Vuejs / Laravel 5.7 API:动作/突变后的组分反应

问题描述 投票:0回答:1

也许你可以帮助我。我搜索并尝试了很多东西。

我有一个带Laravel 5.7 API的Nuxtjs项目(用于auth的JWT Auth)。用户可以CRUD一个帖子。一切正常或差不多。当前用户创建帖子后,在他的帖子被索引的页面上被重定向。但有时创建的新帖子出现,有时不出现,我在控制台日志和服务器端没有错误,创建的帖子存在于数据库中。当我刷新页面时,新帖子呈现。这是随机的。删除操作也是一样的。

我将NuxtJs与Vuex用于商店。我用dispatch调用我的组件方法中的动作。动作调用axios put或delete方法,我提交一个变异来更新state.posts数组。在发送之后,我用NuxtJS的auth模块重新获取用户以重新加载用户的帖子。并推动路线。

就在执行删除操作的下方,向您展示我的逻辑。

我的组件方法:

deletePost(post) {
  this.$toast.show('Do you really want to remove this post ?', {
    duration: 5000,
    icon: 'check',
    action: [
      {
        text: 'No',
        onClick: (e, toastObject) => {
          toastObject.goAway(0)
        }
      },
      {
        text: 'Yes',
        onClick: (e, toastObject) => {
          this.$store.dispatch('posts/deletePost', post).then(() => {
            console.log('here')
            this.$auth.fetchUser()
            this.$router.push({ path: '/:account/posts' })
          })
          this.$toast.show('Post successfully removed', {
            icon: 'check'
          })
          toastObject.goAway(0)
        }
      }
    ]
  })
},

商店行动:

deletePost({ commit }, post) {
    this.$axios
      .delete(`/posts/${post.id}`)
      .then(res => {
        console.log(res.data)
        if (res.data.message === 'success') commit('DELETE_POST', post)
      })
      .catch(err => {
        console.log(err)
      })
  }

商店突变:

DELETE_POST(state, post) {
    const index = state.posts.findIndex(item => item.id === post.id)
    state.posts.splice(index, 1)
  }
vue.js vuejs2 vuex nuxt.js nuxt
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.