【问题标题】:Data not showing on vue.js component using laravel api使用 laravel api 在 vue.js 组件上未显示数据
【发布时间】:2021-02-26 18:13:59
【问题描述】:

我正在尝试使用 API 从数据库中获取数据,但我的 vue 控制器上没有输出。

我这样做对吗?

我认为我分配 scheduleList 的方式有误。

我对 vue.js 和 API 很陌生,我想知道我在这里做错了什么。

控制器

public function schedules(){ 
    return Schedule::all(); 
}

api.php

    Route::get('schedules', 'CalendarController@schedules');

Vue 组件

    <script>
    import axios from 'axios'
    
    export default {
    
      data() {
        return {
          schedules: [],
    
          scheduleList: [
             {
            id: schedules.id,
            title: schedules.title,
            category: schedules.category,
            start: schedules.start,
            end: schedules.end
            },
          ],
    
        };
      },
     
      methods: {
       
        loadSchedules() {
         axios.get('/api/schedules')
         .then((response) => {
           this.schedules = response.data;
         })
         
        }
      },
      mounted() {
        this.loadSchedules();
      }
    };
    </script>
    <style>
    </style>

【问题讨论】:

  • 您如何显示该列表?
  • 我认为这是因为您正在为 scheduleList 分配尚不存在的值
  • 我正在使用 tui.calendar。但我认为问题在于如何分配值 id:schedule.id。这是正确的方法吗?
  • 我收到错误 ReferenceError: schedules is not defined
  • 将您的 loadSchedules 添加到 created() 中,然后将 async await 添加到您的 loadSchedules 函数中。

标签: laravel api vue.js vue-component


【解决方案1】:

问题出在您的数据选项中,因为您引用的是未定义的 schedules,我确定您的意思是 this.schedules,但这样做并不能解决问题,因为首先呈现 this.schedules 是一个空数组,如果schedules 属性是一个数组,我推荐使用以下解决方案:

<script>
import axios from 'axios'

export default {

  data() {
    return {
      schedules: [],

      scheduleList: [],

    };
  },
 
  methods: {
   
    loadSchedules() {
     axios.get('/api/schedules')
     .then((response) => {
       this.schedules = response.data;
  
      let schedule=this.schedules[0]
     
    this.scheduleList.push({
        id: schedule.id,
        title: schedule.title,
        category: schedule.category,
        start: schedule.start,
        end: schedule.end
        })

     })
     
    }
  },
  mounted() {
    this.loadSchedules();
  }
};
</script>

【讨论】:

    【解决方案2】:

    如果你做出承诺,总是会发现错误。

    loadSchedules() {
         axios.get('/api/schedules')
         .then((response) => {
           this.schedules = response.data;
         })
         .catch(error => {
           console.log(error)
         })
    

    在您的错误中,您可以更好地了解问题所在。 另一种方式是浏览器中的“网络”选项卡,您可以在其中跟踪您的 api 请求

    【讨论】:

    • 是的,我在原始代码中发现了错误。我刚刚删除了它,以便这里的代码更短。我在网络标签上看不到任何错误。
    • 然后尝试将 console.log(error.response) 作为 catch 中的输出
    猜你喜欢
    • 2019-03-27
    • 2020-04-09
    • 2021-03-02
    • 2017-07-19
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多