You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 23:57:03