简体   繁体   English

Vue.js:我可以使用 v-if 创建组件吗?

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

I'm new to front end development and am experimenting with learning Vue.js.我是前端开发的新手,正在尝试学习 Vue.js。 Suppose I have an array假设我有一个数组

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

and I have a component named FruitPrices which can work like:我有一个名为 FruitPrices 的组件,它可以像这样工作:

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

I was wondering would it be possible to use v-if to create multiple components?我想知道是否可以使用 v-if 创建多个组件? 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!这段代码不起作用,所以我想知道是否有任何有 Vue 经验的人可以帮我一把!

When going through a loop in Vue Js it is required to have a key.在 Vue Js 中进行循环时,需要有一个键。 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:例如,如果你有fruits = [{id:1, name: London}, {id:2, name: New York}]你可以做v-for="item in fruits":key="item.id"但是因为你没有它,所以最好的选择是下面的一个:

<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 Vue js 会将索引视为数组中每个项目的 position

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

you can use v-for in component tag您可以在组件标签中使用 v-for

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>你必须使用:fruit prop之前,因为你不是传递一个字符串,而是一种变量,

<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.顺便说一句,与您有关 v-if 的问题有关,将 v-if 与 v-for 一起使用并不是一种好的过滤方法,最好的方法是使用计算属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM