【问题标题】:Data doesn't show in console.log but renders fine in template数据未显示在 console.log 中,但在模板中呈现良好
【发布时间】:2018-04-27 06:36:33
【问题描述】:

我有一个 Vue 组件,我在其中进行 axois 调用以获取所有员工数据,将其存储在数组中,并将其显示在表格中。效果很好。

我感到困惑的行为可以在下面的 getEmployees() 方法中看到,其中我有 console.log(this.employees);

当我检查控制台时,那里返回的对象是空白的并且没有任何员工数据,即使在模板中迭代时相同的数据对象正在显示所有员工数据。

看看代码:

<template>
    <b-table striped hover :items="employees"></b-table>
</template>

<script>
    export default {
        data() {
            return {
                employees: []
            }
        },

        methods: {
            getEmployees() {
                axios.get('/api/employees')
                    .then(response => this.employees = response.data)

                console.log(this.employees);
            }
        },

        created() {
            this.getEmployees()
        }
    }
</script>

我在那里做 console.log 的原因是因为我想遍历该数据并将该数组中的所有薪水数据格式化为货币格式(即千位后的逗号、货币符号等)

有什么想法吗?

谢谢。

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    您为 this.employees 赋值的范围在 promise 的 .then() 方法中。尝试扩展您的箭头函数,然后在 .then() 方法中放置 console.log() 调用。

    <template>
        <b-table striped hover :items="employees"></b-table>
    </template>
    
    <script>
        export default {
            data() {
                return {
                    employees: []
                }
            },
    
            methods: {
                getEmployees() {
                    axios.get('/api/employees')
                        .then((response) => {
                            this.employees = response.data;
                            console.log(this.employees);
                          }
                       )
    
    
                }
            },
    
            created() {
                this.getEmployees()
            }
        }
    </script>
    

    在 .then() 之后,您应该进行其余的更改。

    【讨论】:

    • 哦,哇,谢谢。这行得通。我会尽快接受答案。让我。
    • 我(错误地)假设由于 Vue 的反应式状态管理特性,一旦设置了它们的值,我就可以访问它们。我想一般来说,养成以你的方式处理轴突响应的习惯可能是最佳实践。
    • @Kopty,问题是 .then() 是异步调用的,在ajax调用解决后,.then()之外/之后的代码被同步调用,不会等待.then()内的代码被执行。您也可以 watch 属性 this.employees 进行更改,而不是在 .then() 句柄中更改它,但请记住,这可能会使性能过载。
    猜你喜欢
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2022-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    相关资源
    最近更新 更多