Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
907 views
in Technique[技术] by (71.8m points)

vue.js - `TypeError: Cannot read property 'length' of null` in vuejs when data fetch from api

I'm using in bootstrapvue, I have an API that data coming from it, please see codes below, I will explain more:

      <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
      )
    },
  },

a bit of what I want to do: as you can see in the code above, I want to have pagination which items mix with it, I mean the number of items that have shown be under the control of pagination. well, when I give rows computed property to :total-rows it returns an error, that I think because API isn't loaded on rows yet, but when writing on the template or console something like this as I did as on computed rows posts.length', everything works fine, but on :total-rows` game me this error:

TypeError: Cannot read property 'length' of null

I'm using nuxtjs


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should initialize your posts property with an empty array :

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

then compare the length to 0 :

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

or just do :

 if (this.posts.length) {

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...