Laravel + Vue + Axios:即使'this'更新,DOM也不会从Axios调用中更新

时间:2019-08-20 11:58:15

标签: laravel vue.js axios

我正在学习Laravel + Vue。我遇到了一个非常奇怪的问题:

<template>
    <div class="container">
        <li v-for='category in categories' v-bind:key='category.id'>
            {{ category.title }}
        </li>
        {{ test }} 
    </div>    
</template>

<script>
    export default {
        name: 'ExampleComponent',
        data() {
            return {
                categories: [],
                test: "test"
            }
        },
       mounted() {
            this.categories.push({'title': 'test1', 'desc': 'test1 desc'}, {'title': 'test2', 'desc': 'test2 desc'});
            this.test = "fwibble";
            axios.get('/api/categories')
            .then(response => {
                console.log(response);                
                this.test = "wibble";
                this.categories = response.data;
                console.log(this);
            });
        }
    }
</script>

运行它时,会发生以下情况:

第一个this.categoriesthis.title的行为符合预期。该页面显示两个虚拟类别,并且{{test}}设置为“ fwibble”。

所有console.logs触发。

当我console.log response时,它看起来像预期的一样(后端有几个类别) 当我console.log this时,看起来好像已更新(因此测试:摆动,并且类别包含来自后端的数据数组)

但是,不会显示新数据。就像我无法从axios调用中更改DOM。

在搜索解决方案时,最常见的问题是“ this”不是预期的结果,但是我使用“ this”引用了正确的东西(在console.logs中已选中)

以防万一与更广泛的项目有关,这是我的仓库:https://github.com/StarfallProjects/scheduler

我正在使用npm run watch

运行前端

在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您的应用程序在layout.blade.php中安装了两次,因为它有两个app.js脚本标签(在第13行和第79行)。

您应删除第二个脚本,因为第一个脚本标签已延迟;页面解析完成后将执行该操作。

另外,您可能会遇到一些错误,因为您有两个ID为app的元素。第一个在layout.blade.php,另一个在welcome.blade.php。您可以删除第二个,因为这是不必要的。