Nopmd
Nopmd

Reputation: 67

Using a variable with v-for in Vue3 template

This code works when I change {{num_bottom}} to 5, but I prefer to use a variable. Could you please suggest why it is not correct and how to fix it? I am using Vue3.

<template>

            <tr class="row" v-for="rowIdx in Math.ceil(items.length / {{num_bottom}})">

</template>

  <script  setup>   
   const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   let num_bottom = 5    
  </script>

If I change {{num_bottom}} to a number such as 3, it works. I want to use a variable so that I can change it in one place and it will affect everything.

Upvotes: 1

Views: 304

Answers (1)

noah1400
noah1400

Reputation: 1509

They way you have written it num_bottom is being treated as a string instead of a variable.

To fix your mistake remove the curly braces around num_bottom. Make sure num_bottom is inside the templates scope, you can do that by declaring it in the setup function.

<template>
  <tr class="row" v-for="rowIdx in Math.ceil(items.length / num_bottom)">
</template>

<script>
  export default {
    setup() {
      const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
      const num_bottom = ref(5)
      
      return {
        items,
        num_bottom
      }
    }
  }
</script>

Upvotes: 1

Related Questions