【问题标题】:strange console.log output with vuex带有 vuex 的奇怪 console.log 输出
【发布时间】:2021-08-13 15:32:04
【问题描述】:

我有一些简单的 vuex 商店

const state = {
    todos : []
}

const getters = {
    allTodos: (state) => state.todos
}

const actions = {
     async fetchTodos({ commit }) {
        console.log(this.state.todos)
        if(state.todos.length == 0) {
                const response = await axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5')
                commit('setTodos', response.data)
        }         
    }
}

const mutations = {
    setTodos(state, todos) {
        state.todos = todos
    }
}

为什么 fetchTodos 操作输出中的 console.log 在填充了 axios.get 和 setTodos 突变之前填充了 todos?

当我写作时

const actions = {
     fetchTodos({ commit }) {
        console.log(this.state.todos)
        setTimeout(async () => {
            if(state.todos.length == 0) {
                const response = await axios.get('https://jsonplaceholder.typicode.com/todos?_limit=5')
                commit('setTodos', response.data)
            }
        }, 10000)    
    }
}

输出正常,状态为空 todos

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    这是因为您会在控制台日志旁边看到一个蓝色小三角形。我不知道它的技术术语,但发生的情况是浏览器将使用当前值更新该变量,因为它是一个反应变量,并且由于它是指向内存中某个位置的引用,它会更新。

    如果你真的希望看到价值并证明上面描述的内容,你可以写:

    console.log(JSON.parse(JSON.stringify(this.state.todos)));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-24
      • 2022-07-08
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      相关资源
      最近更新 更多