嗨,我正在尝试在 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/