Axios-在vuex操作中从api获取数据吗?

时间:2020-09-04 14:05:32

标签: vue.js axios vuex

如何正确执行转移或重写该功能的操作,这些操作将从每个相册接收第一张照片?

我的照片模型:

import { api } from "@/apis/config";
const endPoint = 'photos'
const state = {
    photos: []
}
const getters = {}
const mutations = {
    SET_PHOTOS(state, data) {
        state.photos = data
    }
}
const actions = {
    loadMore(id) {
        api.get(`photos?albumId=${id}`).then(response => {
            return response.data[0].thumbnailUrl;
        });
    }
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
};

还有我的相册组件:

...
<script>
import {mapActions} from "vuex";
export default {
  name: "GridAlbums",
  props: ['album'],
  data() {
    return {
      loading: true,
      errored: false,
      photo: null
    }
  },
  mounted() {
    this.photo = this.loadMore(this.album.id)
  },
  methods: {
    ...mapActions("photos", ["loadMore"])
  }
}
</script>
...

这是我的api配置文件,其中VUE_APP_HOST为https://jsonplaceholder.typicode.com/

import axios from 'axios'

export const api = axios.create({
    baseURL: process.env.VUE_APP_HOST,
})

api.interceptors.response.use(
    response => {
        return response
    },
    error => {
        return Promise.reject(error)
    }
)

如果您以这种方式获取数据,那么一切都会如期进行: Getting data from jsonplaceholder.typicode.com

1 个答案:

答案 0 :(得分:0)

尝试在vuex动作中添加async / await,因为动作必须是异步的,并且存储和突变都是同步的。

也可以使用try / catch来代替Promise这样可以使代码更清洁