vuejs用ajax取回的数据不能渲染

这样可以正常渲染:

<div class="container" id="app">
    <ol>
        <li v-for="(todo,index) in todos">
            {{ index }} {{ todo.text }}
        </li>
    </ol>

</div>

<script>
    new Vue({
        el: '#app',
        data: {
            todos: [
                { text: 'Learn JavaScript' },
                { text: 'Learn Vue' },
                { text: 'Build something awesome' }
            ]
        }
    });
</script>

下面把数据改为ajax(使用的axios发送ajax请求:https://github.com/mzabriskie...取回,就不能显示在html中了,console.log(response);是能够看到取回的数据的。

<div class="container" id="app">
    <ol>
        <li v-for="(todo,index) in todos">
            {{ index }} {{ todo.text }}
        </li>
    </ol>

</div>

<script>
    new Vue({
        el: '#app',
        data: {
            todos: []
        },
        mounted: function () {
            this.$nextTick(function () {
                axios.get('/articles')
                    .then(function (response) {
                        console.log(response.data);
                        this.todos = response.data;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            });
        }
    });
</script>

console.log(response.data);是这样的:
clipboard.png
...]

下面这样模拟是可以工作的:

<div class="container" id="app">
        <ol>
            <li v-for="(todo,index) in todos">
                {{ index }} {{ todo.text }}
            </li>
        </ol>
    
    </div>
    
    <script>
        new Vue({
            el: '#app',
            data: {
                todos: []
            },
            mounted: function () {
                this.$nextTick(function () {
                    var arr=[
                        { text: 'Learn JavaScript' },
                        { text: 'Learn Vue' },
                        { text: 'Build something awesome' }
                    ];
                    this.todos = arr;
                });
            }
        });
    </script>
阅读 10k
8 个回答

你这里所用的this的环境变量是next()的回调函数 在调用this.nextTick之前保存一下Vue实例的变量吧

要先了解一下this这个关键字吧...
可以把 this 存起来:

mounted() {
        let self = this;
        self.$nextTick(()=>{
            axios.get('/articles')
                .then((response)=>{
                    self.todos = response.data;
                });
        });
    }

检查response.data格式是否正确,很可能是这个问题。

获取的数据json.parse一下?

使用 es6 的箭头函数 解决 this 问题.

存一下this

理解一下this所指向的context

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏