【问题标题】:How to cleanly call an API that requires store data如何干净地调用需要存储数据的 API
【发布时间】:2020-10-01 23:05:12
【问题描述】:

我目前在尝试访问需要以状态存储数据的单独 api 时遇到困难。但是,从中获取数据所需的数据需要首先启动。基本上,它几乎就像一个初始设置,将在 vuex 中构建我的状态。这是一个例子:

使用 axios 获取组织数据,然后获取(获取)另一组需要组织数据的数据。

这是商店文件:

import axios from 'axios'

export const state = () => ({
  currentBoard: [],
  ideas: []
})

export const actions = {
  async fetchOrganization({ commit }) {
    const response = await axios
      .get('https://api.getconflux.com/api/v1/organizations/url/ideas')
      .then((res) => res.data)

    commit('add', response)
  },
  async fetchIdeas({ commit }, parameters) {
    const { id, board } = parameters
    const response = await axios
      .get(
        `https://api.getconflux.com/api/v1/public/${id}/ideas?limit=10&page=1&statusId=&q=&orderBy=popularityScore&categoryId=&boardId=${board}`
      )
      .then((res) => res.data)

    commit('addIdeas', response)
  }
}

export const mutations = {
  add(state, board) {
    state.currentBoard = board
  },
  addIdeas(state, ideas) {
    state.ideas = ideas
  }
}

正如您在此处看到的,我已将actions 彼此分开。当用户点击董事会页面时。在我的情况下https://localhost:3000/boardname,它应该启动fetchOrganization,然后,一旦在currentBoard 中设置了组织状态,我想调用fetchIdeas,然后将数据存储在状态中。

这是我的董事会视图:

<template>
  <div>
    <p>This is {{ $route.params.board }}</p>
    <p>{{ board }}</p>
    <p>{{ ideas }}</p>
  </div>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  name: 'Boards',
  computed: {
    board() {
      return this.$store.state.boards
    },
    ideas() {
      return this.$store.state.ideas
    }
  },
  created() {
    this.$store.dispatch('boards/fetchOrganization')
    if (this.$store.state.boards.currentBoard.id) {
      this.$store.dispatch('boards/fetchIdeas', {
        id: this.$store.state.boards.currentBoard.id,
        board: this.$store.state.boards.currentBoard.IdeaBoards[0].id
      })
    }
  },
  methods: {
    ...mapActions({
      fetch: 'boards/fetchOrganization',
      fetchIdeas: 'boards/fetchIdeas'
    })
  }
}
</script>

这似乎不起作用,因为当我调用 fetchIdeas 时,状态中的 currentBoard 不可用。有没有更好的方法,或者我完全错过了什么?

谁能指出我正确的方向,或者让我知道进行此类呼叫的最佳做法是什么?

提前致谢,任何帮助将不胜感激!

【问题讨论】:

  • 您应该使用mounted 挂钩而不是created 挂钩,它可以访问商店!更好的方法是使用asyncDatafetch
  • 检查这个:forum.vuejs.org/t/…
  • fetch: 'boards/fetch' 但是你在 vuex 中没有 fetch 操作?是错字吗?它应该是fetch: 'boards/fetchOrganization'?你应该在调用 fetchIdeas 之前等待 this.$store.dispatch() 的 fetchOrganizations
  • 谢谢大家! @HongJian 是的,我对错字表示歉意,我已经更正了!

标签: vue.js axios vuex nuxt.js


【解决方案1】:

你可以学习更多关于如何使用mapState、mapActions、mapGetters等

https://vuex.vuejs.org/guide/

<template>
  <div>
    <p>This is {{ $route.params.board }}</p>
    <p>{{ board }}</p>
    <p>{{ ideas }}</p>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex';

export default {
  name: 'Boards',
  computed: {
    ...mapState({
      boards: state => state.boards,
      ideas: state => state.ideas
    })
  },
  async created() {
    await this.fetchOrganization();
    if (this.boards.currentBoard.id) {
      this.fetchIdeas({
        id: this.boards.currentBoard.id,
        board: this.boards.currentBoard.IdeaBoards[0].id
      });
    }
  },
  methods: {
    ...mapActions({
      fetchOrganization: 'boards/fetchOrganization',
      fetchIdeas: 'boards/fetchIdeas'
    })
  }
};
</script>

【讨论】:

    【解决方案2】:

    我建议您在调用时使用promise,因为您需要等待异步调用完成,然后再尝试访问其数据。

    created() {
        Promise.all([
            this.$store.dispatch('boards/fetch')
        ]).finally(() => {
            if (this.$store.state.boards.currentBoard.id) {
                this.$store.dispatch('boards/fetchIdeas', {
                   id: this.$store.state.boards.currentBoard.id,
                   board: this.$store.state.boards.currentBoard.IdeaBoards[0].id
                })
            }
        });
    },
    

    【讨论】:

    • 谢谢我的人,你帮了我。请问为什么这是更好的方法?另外,除了对每个状态项使用 this.$store.state.boards... 之外,我还能做些什么吗?
    • 你可以使用你的计算属性,所以this.board.currentBoard.id。我建议使用 Promise,因为它们会在触发下一个事件之前等待您的异步任务完成。如果您采用您的方法,if 语句将永远不会捕获任何内容,因为它不会等待您的异步任务完成。
    • created 挂钩更适合获取初始数据。 “在 created 钩子中,您将能够访问响应式数据并且事件处于活动状态。模板和虚拟 DOM 尚未安装或渲染。”
    • 您在问题当前状态下的正确@ZedHome,使用created 确实比mounted 更好。我将编辑我的答案
    猜你喜欢
    • 2011-08-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 2019-11-22
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    相关资源
    最近更新 更多