首页 > 解决方案 > Vue数据不在控制台上显示值,但在组件上显示

问题描述

我正在尝试检索全局会话值并将其设置为 vue 变量。问题是, id 变量没有在控制台上显示任何值,而是在 vue 组件上显示值。我已经检查了 vue devtools 并且 id 确实包含正确的值。

Vue 组件

<template>
  <div class="container">
    <h1>{{id}}</h1> // the id does displays the value
  </div>
</template>

<script>
export default {
    data () {
        return {
          id:'',
        }
    },
    created(){
        axios.get('api/studentlecture').then(response => this.id = response.data).catch(function(error){console.log(error)
        });     
        console.log(this.id) 
    },
    methods:{

    },
    mounted() {
        console.log('Component mounted.')
    }
}

控制器

public function index()
{
    $id= session('userID');
    return json_encode($id);
}

标签: phplaravelvue.jslaravel-artisan

解决方案


因为axios调用是异步的。JavaScript 引擎将执行 axios 请求,并在等待期间继续执行代码。

您正在尝试登录this.id,而它尚未被分配。如果要记录该值,则必须将其放入 axios 函数的回调中。

axios.get('api/studentlecture')
    .then(response => {
        this.id = response.data;
        console.log(this.id); // <== Here
    })
    .catch(function(error){console.log(error)}); 

推荐阅读