Ahmad Mobaraki
Ahmad Mobaraki

Reputation: 8160

VueJs computed method error: Cannot read property 'words' of undefined"?

This is my pseudo code:

var vm = new Vue({
  el: '#test',
  data: {     
    words: [{name:'1'},  {name:'2'}, {name:'3'},{name:'4'},{name:'5'},{name:'6'}],
  },
  computed: {
    paginatedWords: function (words) {
      return vm.words.slice(2, 2);
    }
  }
});

I want to show only a portion of words with v-for, Here is the Html:

<ul>
  <li v-for="w in paginatedWords"> @{{w.name}} </li>
</ul>

But console gives me this error :

Error in render function: "TypeError: Cannot read property 'words' of undefined"

What am I doing wrong?

Upvotes: 1

Views: 4802

Answers (1)

Bert
Bert

Reputation: 82439

Use this, not vm.

paginatedWords: function () {
  return this.words.slice(2, 2);
}

Also, slice(2,2) will return an empty array. The first argument is where to start and the second is where to end. See slice.

Finally, the words argument is ignored.

var vm = new Vue({
  el: '#test',

  data: {
    words: [{
      name: '1'
    }, {
      name: '2'
    }, {
      name: '3'
    }, {
      name: '4'
    }, {
      name: '5'
    }, {
      name: '6'
    }],

  },

  computed: {
    paginatedWords: function() {
      return this.words.slice(2, 4);
    }
  }
});
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="test">
  <ul>
    <li v-for="w in paginatedWords"> {{w.name}} </li>
  </ul>
</div>

Upvotes: 4

Related Questions