laravel - 如何将数据作为多个对象返回?
问题描述
我在状态内设置了一个空数组
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);
当我加载页面时,能够控制台日志作业,但状态没有得到更新。
如何成功将数据推送到状态?
解决方案
尝试使用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));
推荐阅读
- javascript - 如何更改嵌入文本的字体大小
- jsf - 检查复选框菜单中的选定项目
- sql - 尝试将外键添加到现有表时出现模糊错误
- kubernetes - 强制 kubernetes 入口 cname 格式
- react-native - 如何在 React Native 中加入 2 个堆栈导航器
- php - laravel 5.5 禁止/停用用户
- r - 将数字存在的位置更改为 1
- javascript - 如何使用 Javascript 以块(流)的形式播放来自 url 的音频
- javascript - 如何在网页中的按钮上有一个突出显示的小图标来显示新的更新?
- python - 将钱分成票据的功能