嗨我想在一个laravel应用程序中使用Vue但我有一些问题 . 基本上我需要从get请求中检索数据并根据它构建一些结果 . 问题是我甚至无法正确检索数组变量中的数据 . 我更好解释一下
在我的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>
页面加载但我得到一个错误,表示结果var未定义 . 如何用get数据填充结果var?什么是正确的方法呢?
2 回答
这是一个范围问题 . 在你的代码中,回调中的
this
指的是函数本身,而不是vue实例,所以它是undefined
. 要解决此问题,您应该使用箭头函数(Laravel已经正确配置了ES6),这将确保this
引用vue实例:javascript中的
this
由所谓的函数决定,而不是它定义的位置 . 解决问题的一种方法是使用var self = this;
将this
的引用存储在另一个变量中,然后像self.results = resp.data;
那样引用结果使用
bind
函数的另一种方法是Arrow函数 . 使用箭头函数,其范围将更改为词法定义的位置 .