Vue.js: Can I use v-if to create components?

Viewed 92

I'm new to front end development and am experimenting with learning Vue.js. Suppose I have an array

fruits = ["New York", "Chicago", "London"]

and I have a component named FruitPrices which can work like:

<FruitPrices fruit="London"></FruitPrices>

I was wondering would it be possible to use v-if to create multiple components? Something along the lines of:

<div v-for="item in fruits" : key="item">
    <FruitPrices fruit="item"></FruitPrices>
</div>

This code does not work so I was wondering if anyone experienced with Vue can lend me a helping hand!

3 Answers

When going through a loop in Vue Js it is required to have a key. For instance, if you had fruits = [{id:1, name: London}, {id:2, name: New York}] you could have done v-for="item in fruits" :key="item.id" but because you dont have it the best option is the one below:

<div v-for="(item, index) in fruits"  :key="index">
    <FruitPrices fruit="item"></FruitPrices>
</div>

Vue js is going to consider index as the position of each item in the array

<FruitPrices fruit:"item" v-for="(item,index) in fruits" :key="index">
</FruitPrices>

you can use v-for in component tag

here is your component:

<template>
  <div>
    <div v-for="item in fruits" :key="item">
      <FruitPrices :fruit="item"></FruitPrices>
    </div>
  </div>
</template>
<script>
import FruitPrices from "../somePlace/FruitPrices";
export default {
  components: { FruitPrices },
  data: () => ({ fruits: ["New York", "Chicago", "London"] })
}
</script>

In this line <FruitPrices fruit="item"></FruitPrices> you must use : before the fruit prop, because you are not passing a string, but a kind of variable,

<FruitPrices :fruit="item"></FruitPrices>

And you are ready to show the fruit's price in each city!

By the way, related to your question about v-if, using v-if with v-for is not a good way to filter, the best way to do it is using computed properties.

Related