【问题标题】:`TypeError: Cannot read property 'length' of null` in vuejs when data fetch from api`TypeError:当从 api 获取数据时,无法在 vuejs 中读取属性“长度”的 null
【发布时间】:2020-12-31 13:39:35
【问题描述】:

我在 bootstrapvue 中使用,我有一个数据来自它的 API,请看下面的代码,我会解释更多:

      <b-pagination
        v-model="currentPage"
        :total-rows="rows"
        :per-page="perPage"
        aria-controls="itemList"
        align="center"
      ></b-pagination>
    export default {
      data() {
        return {
          posts: null,
          perPage: 1,
          currentPage: 1,
        }
      },
  computed: {
    rows() {
      if (this.posts.length >= 1 && this.posts.length !== null) {
        return this.posts.length
      } else {
        return false
      }
    },
    getItemForPagination() {
      return this.posts.slice(
        (this.currentPage - 1) * this.perPage,
        this.currentPage * this.perPage
      )
    },
  },

我想做的一点:正如您在上面的代码中看到的那样,我想要分页哪些项目与之混合,我的意思是显示的项目数在分页的控制之下。 好吧,当我将 rows 计算属性提供给 :total-rows 时,它会返回一个错误,我认为这是因为 API 尚未加载到行上,但是当我在模板或控制台上写入时,就像我在计算 rows 上所做的那样posts.length', everything works fine, but on :total-rows` 游戏我这个错误:

TypeError: Cannot read property 'length' of null

我正在使用 nuxtjs

【问题讨论】:

  • 您应该写下您为调试或/和解决问题所做的工作。

标签: vue.js nuxtjs


【解决方案1】:

你应该用一个空数组初始化你的 posts 属性:

    data() {
    return {
      posts: [],
      perPage: 1,
      currentPage: 1,
    }
  },

然后将长度与0进行比较:

 if (this.posts.length >= 1 && this.posts.length !== 0) {

或者干脆做:

 if (this.posts.length) {

【讨论】:

    猜你喜欢
    • 2018-03-27
    • 2021-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    相关资源
    最近更新 更多