1

我正在尝试学习 vue,但我坚持从 API 获取数据。我正在使用 directusSDK 从 directus 获取数据,并且我能够从 API 获取数据,但我无法将图像 URL 存储在状态的新对象中,有人可以告诉我如何在状态中添加新对象属性并将图像 URL 存储在其上.

这是我的代码

store/modules/models.js
import users  from "./../users"

const state =
{
    models: []
};

const getters =
{
   allModels: state =>state.models

};

const actions =
{
    async fetchModels({ commit }) {
        const response = await users.getItems("models");
        //console.log(response.data);
        commit('_SET_MODELS', response.data);
    },
    async getPic({commit, state}){
        state.models.forEach((element)=>{
            if (element != null) {
                users.getFiles("/Files"+ element.image)
                    .then(response => {
                        element["imgURL"] = response.data[1].data
                    }).then(result => commit('_GET_PIC', result.data)).catch(error => {
                        throw new Error(`API ${error}`);
                    })
            }
        })
    }
 };

const mutations =
{
    _SET_MODELS: (state, models) => (state.models = models),
    _GET_PIC: (state, models) => (state.models = models)
};


export default {
    state,
    getters,
    actions,
    mutations,
}

成功获取 imgUrl 我对我的代码进行了更改,并从 API 获取了 imgUrl,但现在的问题是它没有得到正确的 imgUrl,而是分配了随机的 imgUrl。

这是我更新的代码:

import Vue from 'vue'
import users from "./../users"

const state = {
    models: [],
    picture: []
};

const getters = {
    allModels: state => state.models

};

const actions = {
    async fetchModels({commit}) {
        await users.getItems("models").then(
            response => {
                commit('_SET_MODELS', response.data)
            }
        );
        var arrModels = state.models;
        arrModels.forEach((element, index) => {
            users.getFiles("/Files/" + element.image)
                .then(response => {
                    //console.log(response.data[index].data.full_url);
                    commit('_SET_PIC', {
                        index: index,
                        imgURL: response.data[index].data.full_url
                    });

                })
        })

    }


};


const mutations = {
    _SET_MODELS: (state, models) => (state.models = models),
    _SET_PIC: (state, args) => {
        let index = args.index;
        let imgURL = args.imgURL;
        Vue.set(state.models[index], 'imgURL', imgURL);
    }


};

export default {
    state,
    getters,
    actions,
    mutations,
}
4

1 回答 1

1

根据 Vuex 文档:

更喜欢预先使用所有所需字段初始化商店的初始状态。

但是如果你需要给 Vuex 对象添加一些属性,你必须使用set方法:

Vue.set(obj, 'newProp', 123)

查看官方文档:https ://vuex.vuejs.org/guide/mutations.html#mutations-follow-vue-s-reactivity-rules

您的代码将是这样的:

import Vue from 'vue';
import users from './../users';

const state = { models: [] };
const getters = { allModels: state => state.models };
const actions = {
  async fetchModels({ commit }) {
    const response = await users.getItems('models');
    commit('_SET_MODELS', response.data);
  },
  async getPic({ commit, state }) {
    state.models.forEach((element, index) => {
      if (element != null) {
        users
          .getFiles(`/Files${element.image}`)
          .then(response => {
            console.log('checking if the value is correct', response.data[1].data);
            commit('_SET_PIC', { index: index, imgURL: response.data[1].data });
          })
          // .then(result => commit('_GET_PIC', result.data)) // I don't understand this line
          .catch(error => {
            throw new Error(`API ${error}`);
          });
      }
    });
  },
};
const mutations = {
  _SET_MODELS: (state, models) => (state.models = models),
  // ADD THIS MUTATION
  _SET_PIC: (state, args) => {
    let index = args.index;
    let imgURL = args.imgURL;
    Vue.set(state.models[index], 'imgURL', imgURL);
  },
  _GET_PIC: (state, models) => (state.models = models),
};
export default { state, getters, actions, mutations };

于 2020-02-27T12:00:08.333 回答