How to fix simple error in moving ".slice()" into setup() as a computed function?

Viewed 75

I'm using Vuejs3 and trying to move .slice(0,3) (limits v-for to 3) into a computed function in the setup(), in order to limit the number of elements in a v-for (that happens to be nested in another v-for).

Everything works as intended before the change, using the following code:

<ul class="mt-4">
  <div v-for="review in prime.allReviews" :key="review">
    <li v-for="pro in review.propPros.slice(0, 3)" :key="pro">
      {{ pro }}
    </li>
  </div>
</ul>

When I try to move the slice(0, 3) into the setup() as a computed function, per a dozen suggestions it's best practice to do so, the DOM goes blank. Here's the code causing the problem:

<ul class="mt-4">
  <div v-for="review in prime.allReviews" :key="review">
    <li v-for="pro in limitedPros" :key="pro">
    {{ pro }}
    </li>
  </div>
</ul>

And in setup():

const limitedPros = computed(() => {
      return review.propPros.slice(0, 3);
  });

... 

return {
  limitedPros,
};

Thanks for any help!

1 Answers

Try to pass review to function, without computed property: (When you want to loop review you need to know which one)

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const prime = ref({allReviews: [{propPros: [1,2,3,4,5]}, {propPros: [6,7,8,9]}]})
    const limitedPros = (review) => {
      return review.propPros.slice(0, 3);
    };
    return { limitedPros, prime };
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <ul class="mt-4">
    <div v-for="review in prime.allReviews" :key="review">
      <li v-for="pro in limitedPros(review)" :key="pro">
      {{ pro }}
      </li>
    </div>
  </ul>
</div>

Related