Home > Enterprise >  how can i access data property in html template using loop in vue js
how can i access data property in html template using loop in vue js

Time:10-25

i'm trying to use data property commentsToShow in my html template to limit the amount of data that displays on my webpage

this is my template

<div  v-if="index < products.length" v-for="(commentIndex, index) in computedProduct">
<div >{{products[index].title}}</div>
</div>

if i add commentsToShow in my for loop i get one product but the computed products doesn't work same way the other way round

this my script tag

<script>
export default {
  data() {
    return {
         commentsToShow: 1,
      totalComments: 0,
         
    };
  },

  computed: {
   computedProduct() {
      let tempRecipes = this.products;
      if (this.filterPrice !== "true");  
  }
};
</script>


if i change computed property to commentsToShow this the error i get in my console

The computed property "commentsToShow" is already defined in data.

please how can i get the value of commentToShow in my template

CodePudding user response:

according to vue's official docs it's not recommended to use v-for and v-if on the same element try using v-if on a wrapper div or template element

<div v-for="(commentIndex, index) in computedProduct">
  <template v-if="index < products.length">
    <div >{{products[index].title}}</div>
  </template>
</div>

v-if has higher priority so it's executed first and index will not be defined yet. also you have to return something on your computed property function in order to use it

CodePudding user response:

You can use the slice method on a computed property, like this:

<script>
    export default {
    data() {
        return {
            commentsToShow: 1,
            allComments: []
        };
    },
    computed: {
        listComments() {
            return allComments.slice(0, commentsToShow);
        }
    };
</script>

You can also use pages to show the comments, in this case you can return like this:

return allComments.slice((currentPage - 1) * commentToShow, commentsToShow);

The first argument of slice is the start index, the second is the number of elements to get

  • Related