【问题标题】:Use Vuex in Nuxt在 Nuxt 中使用 Vuex
【发布时间】:2021-01-26 00:42:09
【问题描述】:

我能够使用 Nuxt 的 Fetch API 获取数据并显示它们,但我想改用 Vuex。

存储/index.js:

import Axios from 'axios'

export const getters = {
  isAuthenticated (state) {
    return state.auth.loggedIn
  },

  loggedInUser (state) {
    return state.auth.user
  }
}
export const state = () => ({
  videos: []
})

export const mutations = {
  storeVideos (state, videos) {
    state.videos = videos
  }
}

export const actions = {
  async getVideos (commit) {
    const res = await Axios.get(`https://api.themoviedb.org/3/movie/popular?api_key=${process.env.API_SECRET}&page=${this.currentPage}`)
    commit('storeVideos', res.data)
  }
}

pages/test.vue:

    <template>
          <Moviecards
            v-for="(movie, index) in $store.state.videos"
            :key="index"
            :movie="movie"
            :data-index="index"
          />
    </template>
    
    <script>
...
      fetch ({ store }) {
        store.commit('storeVideos')
      },
      data () {
        return {
          prevpage: null,
          nextpage: null,
          currentPage: 1,
          pageNumbers: [],
          totalPages: 0,
          popularmovies: []
        }
      },
      watch: {
    
      },
      methods: {
        next () {
          this.currentPage += 1
        }
      }
    }
...

当我检查 Vue 开发工具时,数组返回空。

【问题讨论】:

  • state.vidoes 与突变中的state.videos 不同
  • 改正了,但还是一样

标签: javascript vue.js nuxt.js


【解决方案1】:

fetch() 中,您在不带参数的情况下提交storeVideos,这会将store.state.videos 设置为undefined,但我认为您的意思是调度getVideos 操作:

export default {
  fetch({ store }) {
    // BEFORE:
    store.commit('storeVideos')

    // AFTER:
    store.dispatch('getVideos')
  }
}

您的操作也错误地使用了它的参数。第一个参数是 Vuex 上下文,您可以从以下位置解构 commit

export const actions = {
  // BEFORE:
  async getVideos (commit) {}  // FIXME: 1st arg is context

  // AFTER:
  async getVideos ({ commit }) {}
}

【讨论】:

  • 我完全同意async getVideos({commit})是原因