【发布时间】:2019-01-04 20:36:18
【问题描述】:
我是 Vuex js 以及关于商店的一切的新手。
我有以下 store.js
import Vuex from 'vuex'
import Vue from 'vue'
import axios from 'axios';
Vue.use(Vuex)
export const store = new Vuex.Store({
state: {
pacientes: []
},
mutations: {
getPacientes() {
axios.get('http://slimapi/api/pacientes')
.then(response => {
this.state.pacientes = response.data
})
.catch(e => {
console.log(e)
})
}
}
});
然后,当我单击调用此函数的模式(v-dialog)上的按钮时,我会执行提交
agregarTurno()
{
axios.post('/api/pacientes/add', {
...
}).then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
this.$store.dispatch('fetchPacientes')
}
然后我有我的 turno.vue(把它当作 app.vue),在那里我检索了商店的状态。 但是,当提交时,它没有在视图上更新的状态!。
我正在尝试在状态更改时更新视图!
turno.vue
export default {
name: 'turno',
data () {
return {
pacientes: this.$store.state
}
},
created() {
this.$store.commit('getPacientes')
},
mounted() {
this.$store.commit('getPacientes')
},
components: {
tarjetaTurno,
bottomNav,
modalTurno
}
}
我已经准备好一些帖子,其中一些谈论使用计算属性,但我不明白如何以及是否需要在每次状态更改时更新视图。
谢谢大家!
编辑已解决
store.js
export const store = new Vuex.Store({
state: {
pacientes: []
},
mutations: {
setPacientes(state, payload) {
state.pacientes = payload.pacientes
}
},
actions: {
fetchPacientes({commit}) {
axios.get('http://slimapi/api/pacientes')
.then(response => {
commit('setPacientes', {pacientes: response.data}); //After getting patients, set the state
})
.catch(e => {
console.log(e)
})
},
addPacientes(context){
axios.post('/api/pacientes/add', {
nombre: "test",
apellido: "test",
edad: "test",
peso_inicial:"test",
patologia:"test"
}).then(function (response){
context.dispatch('fetchPacientes'); //After adding patient, dispatch the fetchPatient to get them and set state
})
.catch(function (error) {
console.log(error);
});
}
}
});
调用函数添加病人的组件模态:
agregarTurno()
{
this.$store.dispatch('addPacientes');
}
当状态改变时更新的Turno.vue(root)
export default {
name: 'turno',
data () {
return {
pacientes: this.$store.state
}
},
created() {
this.$store.dispatch('fetchPacientes')
},
【问题讨论】:
-
您的突变方法 getPacientes 必须接收状态对象作为参数查看教程:vuex.vuejs.org/guide/getters.html#property-style-access 并且请不要在您的代码中将葡萄牙语与英语混用是一种不好的做法 :) 是的,我是也是巴西人!希望能帮到你!
-
@RamonSchmidt 谢谢!,我已经阅读了文档,但我不明白这种处理状态的方式。谢谢!
标签: javascript vue.js vuejs2 vuex vuex-modules