簡體   English   中英

Vuex狀態的長度不出來

[英]Length of the state of vuex doesn't come out

Vuex中有一個狀態。

我將“圖像”定義為一個數組,當我通過console.log(state.images)打印時,結果如下所示。

[__ob__: Observer]
0: {…}
1: {…}
2: {…}
3: {…}
4: {…}
length: 5
__ob__: Observer {value: Array(5), dep: Dep, vmCount: 0}
__proto__: Array

之后,當我使用console.log(state.images[0])console.log(state.images.length)不起作用時。 您能推薦一些解決方案嗎? 非常感謝您閱讀本文。

編輯)我寫了更多的詳細代碼。

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.. 
            })
},

似乎當vuex未完全保存狀態時,您正在讀取state.images[0]數組。 但是我嘗試使用與您使用的相同的代碼,它對我有用。 嘗試重組您的狀態,以使其不會孤立:


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;

這是codeandbox上的示例代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM