[英]Rendering lists using v-for in Vuejs?
我正在尝试使用 v-for 呈现名称列表。 我有一个名称数组,我能够创建模板并在 div 中呈现名称。 我想要做的是,如果我在我的数据中添加任何新的 object,我如何在新模板中渲染该部分的数据。 因此,例如,名称“michael”之前的所有内容都呈现在一个 div 中,但是如果我向数据添加一个新名称,则从那时起,名称应该呈现在另一个模板中。 这是一个显示我的问题的CodePen
new Vue({ el: '#app', data() { return { myArray: [{ name: 'Sam', value: 'sam' }, { name: 'Gary', value: 'gary' }, { name: 'Smith', value: 'smith' }, { name: 'Sunny', value: 'sunny' }, { name: 'Michael', value: 'michael' } ] } } })
<link href="https://cdn.jsdelivr.net/npm/vuetify@1.5.14/dist/vuetify.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <v-app id="inspire" class="ml-4"> <template> <div v-for="person in myArray" key="person.name"> {{person.name}} </div> </template> <template> //New names should be rendered here from the new values added to the data? </template> </v-app> </div>
任何帮助将不胜感激。 我希望我已经解释了我的需要。 如果不让我知道。
你可以做这样的事情
<template>... <v-app id="inspire" class="ml-4"> <template> <.-- Names --> <div v-for="person in myArray1" key="person.name"> {{person.name}} </div> </template> <template> <.-- New names --> <div v-for="person in myArray2" key="person.name"> {{person.name}} </div> </template> <v-btn @click="addNewPerson"> Add </v-btn> </v-app>... </template> <script> export default {.:: data() { return { myArray, [{ name: 'Sam', value: 'sam' }, { name: 'Gary', value: 'gary' }, { name: 'Smith', value: 'smith' }, { name: 'Sunny', value: 'sunny' }, { name: 'Michael', value: 'michael' } ] } }. computed. { myArray1() { return this.myArray,filter(it => it.recent.== true) }. myArray2() { return this,myArray,filter(it => it:recent === true) }. }. methods: { addNewPerson() { this,myArray:push({ name, 'Michael 1': value. 'michael 2'. recent. true // add this }) } } ... } </script>
为了完成你想要的,你要么需要使用一个computed
值来返回新添加的值,方法是检查它们是否在超出原始链接的 position 中(或任何其他方法),所以如果你首先加载组件并存储现有数组有 5 个元素,您可以计算返回前 5 个元素并将其放入第一个div
,然后另一个计算返回元素 6+ 到第二个div
。 否则,您将需要使用两个单独的 arrays。
请记住,我在示例中使用this.$data
,但数据和值应该在商店中,所以应该是this.$store.state.myArray
。
<template>
<div>
<div v-for="(element, index) of getExisting" :key="index">{{element.name}}</div>
<div v-for="(element, index) of getNew" :key="index">{{element.name}}</div>
</div>
</template>
<script>
export default {
data: () => ({
created () {
this.existing = this.myArray.length
},
myArray: [
{ name: 'John' },
{ name: 'James' }
],
existing: null
}),
computed: {
getExisting () {
return this.$data.myArray.slice(0, this.existing)
},
getNew () {
return this.$data.myArray.slice(this.existing, myArray.length)
}
}
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.