javascript - vue 2 基本测试中未定义的属性

标签 javascript laravel vue.js vuejs2 vue-component

嗨,我正在尝试在 Laravel 应用程序中使用 Vue,但我遇到了一些问题。 基本上我需要从获取请求中检索数据并基于它构建一些结果。 问题是我什至无法正确检索数组变量内的数据。我最好解释一下

在我的 app.js 中,我加载我的 vue 实例

Vue.component('search', require('./components/search.vue'));

const app = new Vue({
   el: '#app',
});

在我的 main.blade.php 中插入我的 vue 组件

<search class="row expanded container"></search>

这是我的 vue 文件

<template>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Example Conhenhmponent</div>

                    <div class="panel-body">
                        I'm an example component!

                        {{test}}

                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {

    data () {
        return {
            test:"this is my sample",
            results: []
        }
    },

    mounted () {
        console.log(this); // here my obj exists  
        console.log('Component mounted.') // it works
        axios.get("http://localhost:8000/api/search?q=qwfqw")
        .then(function(resp){
            if(typeof resp.data == 'string') {
                resp.data = JSON.parse(resp.data);
            }
            console.log(resp.data); // here the object exists
            this.results = resp.data;
        });
    }
}


</script>

页面加载,但我收到一条错误,指出结果变量未定义。 我如何用获取的数据填充我的结果变量?正确的做法是什么?

最佳答案

这是一个范围问题。在您的代码中,回调中的 this 指的是函数本身,而不是 vue 实例,因此它是未定义。要解决这个问题,您应该使用箭头函数(Laravel 已经正确配置了 ES6),这将确保 this 引用 vue 实例:

axios.get("http://localhost:8000/api/search?q=qwfqw")
 .then(resp => {
     if(typeof resp.data == 'string') {
         resp.data = JSON.parse(resp.data);
     }
     console.log(resp.data); // here the object exists
     this.results = resp.data;
 });

关于javascript - vue 2 基本测试中未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42790508/

相关文章:

javascript:检测用户是否被重定向到该页面

mysql - 无法存储新行 - SQLSTATE [23000] : Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

performance - PhpStorm 在编辑 vue.js 文件时速度极慢

Vue.js:如何更新对象数组?

javascript - 可以使用for循环在jquery中创建 'else if'语句吗

javascript - 在 JavaScript Canvas 上旋转各个三 Angular 形

javascript - jquery协助获取ms-vb2的子字符串

javascript - jQuery keydown 后访问属性

laravel - Eloquent ORM 性能

vue.js - 使用 vue-cli3 移除插件