首页 > 解决方案 > 如何将数据作为多个对象返回?

问题描述

我在状态内设置了一个空数组

const state = {
    jobs: []
}

在组件内部,我调度了一个动作,代码如下所示:

created(){
    this.$store.dispatch('viewJobs');
}

viewJobs 操作如下所示:

viewJobs: ({commit}) => {

    axios.get('/api/jobs')
        .then(res => {
            const jobss = res.data;

            console.log(jobss);

            commit('LIST_JOBS', jobss);

        })
        .catch(error => console.log(error));   
}

然后突变看起来像这样:

'LIST_JOBS'(state, jobss){
    state.jobs.push(jobss);
}

从 laravel 方面来看,我的控制器如下所示:

    $jobs = Employment::all();

    return $jobs->toJson(JSON_PRETTY_PRINT);

当我加载页面时,能够控制台日志作业,但状态没有得到更新。

如何成功将数据推送到状态?

标签: laravelvuex

解决方案


尝试使用response()->json()

return response()->json(Employment::all(),200);

并尝试{jobss:jobss}在提交部分使用

viewJobs: ({commit}) => {

    axios.get('/api/jobs')
        .then(res => {
            const jobss = res.data;

            console.log(jobss);

            commit('LIST_JOBS', {jobss:jobss});

        })
        .catch(error => console.log(error));   
}

另一种方式,您的 vuex 商店看起来像这样

// state
export const state = () => ({
    items: []
})

// getters
export const getters = {
    items: state => state.items
}

// mutations
export const mutations = {
    SET_ITEMS (state, { items }) {
        state.items = items
    },
    PUSH_ITEM (state, { item }) {
        state.items.push(item)
    },
    UPDATE_ITEM (state, { index, item }) {
        state.items[index] = item
    },
    DELETE_ITEM: (state, index) => {
        state.items.splice(index.index, 1);
    }
}

// actions
export const actions = {
    setItems ({ commit }, { items }) {
        commit('SET_ITEMS', { items })
    },
    pushItem ({ commit,state }, { item }) {
        commit('PUSH_ITEM', { item })
    },
    deleteItem ({ commit,state }, { index }) {
        commit('DELETE_ITEM', { index })
    },

    updateItem ({ commit,state }, { index,item }) {
        commit('UPDATE_ITEM', { index,item })
    },
}

然后在您的组件中调用您的操作

 this.$axios.$get('/api/jobs')
        .then(res => {
            const jobss = res.data;

            console.log(jobss);

            this.$store.dispatch('your_store_name/setItems', {items:jobss});

        })
        .catch(error => console.log(error));

推荐阅读