在Laravel中使用Vue.js无法将数据存入tweets数组,问题出在哪里?
问题根源
- 核心错误是
then回调中使用普通函数导致this指向偏移,且你代码中使用的未定义变量app无法指向Vue组件实例,所以赋值tweets失败 - 同时
async/await和.then混用属于冗余写法,可优化
修复方案
方案1:保留.then写法,改为箭头函数绑定this
箭头函数不会创建独立的this作用域,会继承外层方法的this(即Vue组件实例)
<script> export default { mounted() { this.recupera_post() }, data(){ return{ tweets:[] } }, methods:{ async recupera_post(){ await axios.get('/api/schedulepost') .then((response) => { console.log(response.data) this.tweets = response.data }) } } } </script>
方案2:用async/await标准写法,去掉冗余的.then
这种写法逻辑更清晰,还可以统一捕获请求异常
<script> export default { mounted() { this.recupera_post() }, data(){ return{ tweets:[] } }, methods:{ async recupera_post(){ try { const response = await axios.get('/api/schedulepost') console.log(response.data) this.tweets = response.data } catch (err) { console.error('接口请求异常', err) } } } } </script>
补充注意
请求路径最好加前缀斜杠/api/schedulepost,避免相对路径匹配到错误的路由地址。
内容的提问来源于stack exchange,提问作者carulom
相关产品推荐
相关产品推荐

