【问题标题】:How do I assign an array of objects to an empty array in a Vue component?如何将对象数组分配给 Vue 组件中的空数组?
【发布时间】:2020-12-07 05:16:13
【问题描述】:

我正在尝试编写我的第一个使用 Vue 组件的 Laravel 程序。我正在使用 Laravel 8.x 和 Vue 2.x 并在 Windows 10 上运行。我正在模仿 video,它显示了如何做到这一点。不幸的是,并非他所做的一切都对我有用。昨天这里的一些人在解决我当时遇到的问题时对我很有帮助,但现在我有一个我无法弄清楚的新问题。

他正在使用 Axios 执行 get 请求,以读取先前放入 Vue 组件中的 MySQL 表中的数据。 Axios 返回一个包含数据的响应,然后将其分配给组件的 data() 区域中的一个已初始化的空数组。他将空数组定义如下:

todos: '',

执行axios get的方法如下:

getToDos() {
        debugger;
        axios.get('/todo')
        .then(function (res) {
            if (res.data.length == 0) console.log("Table is empty");
            else {
                this.todos = res.data
            }
            })
        .catch(function (error) {
            console.log(error);
            })
    },

如您所见,他只是将所有 res.data(看起来是一个对象数组)分配给 data() 区域中的 todos 数组。当他执行代码时,它工作正常,但他使用的是 Laravel 7.x,而我使用的是 8.x。当我尝试执行此代码时,Chrome 调试器中出现错误:

TypeError: this is undefined

突出显示赋值语句 (this.todos = res.data)。我还是 Javascript 的新手,我还不熟悉这些成语,但在我看来,todos 好像被定义为一个空字符串并被分配了一个对象数组,所以我真的希望他在执行它时会失败但事实并非如此。也许这与他使用 Laravel 7.x 有关??

不管怎样,我做了一些研究,并在这段代码中尝试了一堆变体,但是当我将某些东西分配给 todos 变量时,我总是收到相同的错误消息,即使我将其定义为

todos: []

todos: new Array()

我尝试编写一个 for 循环并将每个 Object 从 res.data 推送到 todos。没有任何效果。有人可以告诉我为什么他的代码有效以及为什么它不适合我吗?我只是想将 res.data 放在我可以在我的模板中访问的位置,以便我可以显示相关数据。

编辑:这是整个组件。

    <template>
    <div class="container">
        <form @submit.prevent="addTask"> 
            <div class="input-group mb-3 w-100">
                <input type="text" v-model="form.todo" class="form-control" placeholder="Enter new task" aria-label="Enter new task" aria-describedby="button-addon2">
                <div class="input-group-append">
                    <button class="btn btn-success" type="submit" id="button-addon2">Add new task</button>
                </div>
            </div>
        </form>
        <div class="w-25">
            <h1 class="text-white">...</h1>
            <div v-for="todo in todos" :key="todo.id" class="w-100 text-white">
                {{ todo.title }}
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                todos: '',

                form: new Form({
                    title: '',
                })

            } 
        },
        methods: {
            getToDos() {
                debugger;
                axios.get('/todo')
                .then(function (res) {
                    if (res.data.length == 0) console.log("Table is empty");
                    else {
                        this.todos = res.data
                        // var id = 0;
                        // var title = '';
                        // var completed = false;
                        // for (var ix=0; ix<res.data.length; ix++) {
                        //     id = res.data[ix].id;
                        //     title = res.data[ix].title;
                        //     completed = res.data[ix].completed;
                            // var oneToDo = new Object(res.data[ix]);
                            // this.todos.push(oneToDo);
                        // }   
                    }
                    })
                .catch(function (error) {
                    console.log(error);
                    })
            },
            addTask() {
                let data = new FormData();
                data.append('todo', this.form.todo);
                axios.post('/todo', data)
                .then(function (response) {
                    console.log(response);
                    this.form.reset;
                    this.getToDos();
                    })
                .catch(function (error) {
                    console.log(error);
                    })
            }
        },
        mounted() {
            console.log('ToDoComponent mounted.');
            this.getToDos();
        }
    }
</script>

<style lang="scss" scoped>
.container {
    padding-top: 5em;
}
</style>

【问题讨论】:

  • 请分享整个脚本块代码。

标签: javascript laravel vue.js


【解决方案1】:

function(){ //code } 中this 的闭包就是函数本身。如果你想访问你定义函数的对象的this,你需要使用如下箭头函数。

var obj = {
    getToDos() {
       // this here refer to obj
       axios.get('/todo')
        .then( res =>  {
           this.todos =  res.data
       })
    }

}

更多关于 js 中闭包的信息: https://www.w3schools.com/js/js_function_closures.asp https://medium.com/@vmarchesin/javascript-arrow-functions-and-closures-4e53aa30b774

【讨论】:

  • 感谢您对闭包的解释。我以前听过这个词,但不明白它的意思。我已按照您的建议更改了代码,并希望在解决另一个问题后尽快对其进行测试。
  • 现在又过了一个小时,终于把其他问题整理出来,重新测试get;现在工作正常。非常感谢你!我给你打勾,即使 Dhrumil 先回答了,因为你解释了原因:-)
【解决方案2】:

使用箭头功能。像这样 .then 部分

.then((res) => {
    //rest of code
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-10
    • 2013-12-31
    • 1970-01-01
    • 2010-11-22
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    相关资源
    最近更新 更多