【问题标题】:Vue data does not display value on console but does display on componentVue数据不在控制台上显示值,但在组件上显示
【发布时间】:2019-08-15 10:04:58
【问题描述】:

我正在尝试检索全局会话值并将其设置为 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);
}

【问题讨论】:

    标签: php laravel vue.js laravel-artisan


    【解决方案1】:

    因为 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)}); 
    

    【讨论】:

      【解决方案2】:

      发生这种情况是因为 console.log(this.id)axios.get() 可以解决它的承诺之前执行。

      有一些解决方案。

      第一个是将console.log()移动到then()中。

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

      或者您可以使用async/await 等待承诺解决

      async created() { 
        try {
          // This will wait until promise resolve
          const response = await axios.get('api/studentlecture');
          this.id = response.data;
          console.log(this.id);
        } catch(error) {
          console.log(error)
        }
      }
      

      你可以了解更多关于promisehere

      更多关于 async/await 与 promise here的区别

      【讨论】:

        【解决方案3】:

        您可以尝试使用以下代码:

        /*FRONT-END VUE*/
        
        this.axios.get("https://localhost:8000/api/v1/data").then((response)=>{
                            this.data=response.data;
                            console.log(this.data);
                            if(this.data.success){
                              
        
                            }
         });
        /*BACK-END LARAVEL*/
         
         function getData(){
            $result = array('success'=>true,'data'=>$data);
            
            return Response()->json($result);
         }

        【讨论】:

          猜你喜欢
          • 2021-10-23
          • 2022-01-27
          • 1970-01-01
          • 2020-03-11
          • 1970-01-01
          • 2020-09-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多