首页 > 解决方案 > Vue js ajax调用后设置数据

问题描述

我有一个显示用户信息的地方,当页面刷新时,我从 ajax 调用中读取用户信息并设置用户信息数据。但是由于 axios 调用的耗时过程,数据设置是在 DOM 渲染之后执行的。

HTML:

<div> {{user.name}} </div>

Vue.js:

data: function(){
 return {
   user: {},
   }
},

methods: { 

getUserInfo() {
   axios.post(laroute.route('link'), data).then((response) => {
      this.$set(this, 'user', response.data.user);
        },
 },

 mounted() {

        this.getUserInfo();
    }

刷新页面后出现此错误:

"TypeError: Cannot read property 'name' of undefined"

标签: javascriptvue.jsvuejs2vue-reactivity

解决方案


我无法添加评论。您可以尝试更改:

安装为 created 和 this.$set(this, 'user', response.data.user); 对于用户 = response.data.user

无论如何,您可以 console.log 调用结果吗?


推荐阅读