[英]Length of the state of vuex doesn't come out
There is a state in the vuex. Vuex中有一个状态。
I defined 'images' as an array and when I print by console.log(state.images), the result came out like below. 我将“图像”定义为一个数组,当我通过console.log(state.images)打印时,结果如下所示。
[__ob__: Observer]
0: {…}
1: {…}
2: {…}
3: {…}
4: {…}
length: 5
__ob__: Observer {value: Array(5), dep: Dep, vmCount: 0}
__proto__: Array
After that, when I use console.log(state.images[0])
or console.log(state.images.length)
doesn't work. 之后,当我使用
console.log(state.images[0])
或console.log(state.images.length)
不起作用时。 Could you recommend some solution? 您能推荐一些解决方案吗? Thank you so much for reading this.
非常感谢您阅读本文。
EDIT) I write more code in detail. 编辑)我写了更多的详细代码。
const state = {
images:[]
};
const mutations = {
pushPresentImage(state, yo) {
state.images.push(yo);
},
const actions = {
imageLoad() {
},
imageLength({commit}, image){
axios.post('/', ...)
.then(result =>{
commit('pushPresentImage', result.data.image)
})
.then(() => {
console.log(state.images) // it works well like above.
console.log(state.images[0]) // it says undefined..
})
},
Seems like you are reading the state.images[0]
array when the state is not fully saved by vuex. 似乎当vuex未完全保存状态时,您正在读取
state.images[0]
数组。 But I tried with the same code you used and it worked for me. 但是我尝试使用与您使用的相同的代码,它对我有用。 Try restructuring your state so it does not stand alone:
尝试重组您的状态,以使其不会孤立:
import Vue from "vue";
import Vuex from "vuex";
import axios from "axios";
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
todos: []
},
mutations: {
pushPresentImage(state, yo) {
state.todos.push(yo);
}
},
actions: {
imageLoad() {},
imageLength({ commit, rootState }, image) {
axios
.get("https://jsonplaceholder.typicode.com/todos/1")
.then(result => {
commit("pushPresentImage", result.data);
})
.then(() => {
console.log(rootState.todos); // it works well like above.
console.log(rootState.todos[0]); // it does not say undefined..
});
}
}
});
export default store;
Here is the sample code on codesandbox 这是codeandbox上的示例代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.