我试图获得一定的价值;例如,如果我将“ works1”作为此works_id,则我想获取包含“ works1”作为works_id的元素
export default{
images: [{ works_id:'works1',
mother: require('@/assets/works/works1-0.png'),
children: [require('@/assets/works/works1-1.png')
, require('@/assets/works/works1-2.png'), require('@/assets/works/works1-3.png'), require('@/assets/works/works1-4.png')]},
{ works_id:'works2',
mother: require('@/assets/works/works2-0.png'),
children: [require('@/assets/works/works2-1.png')
, require('@/assets/works/works2-2.png'), require('@/assets/works/works2-3.png'), require('@/assets/works/works2-4.png'), require('@/assets/works/works2-5.png')]}
]
}
<template>
<div class="deWorks">
<div>
<img :src="getWorksImgs.mother">
</div>
<div v-for="(Img , index) in getWorksImgs.children" :key="index">
<img :src="Img">
</div>
</div>
</template>
<script>
import StoreWorks from '@/store/works'
export default {
data(){
return {
worksImgs : StoreWorks.images,
works_id: this.$route.params.works_id
}
},
computed: {
getWorksImgs(){
let worksImgs = this.worksImgs
// let works_id1 = this.$route.params.works_id
worksImgs= worksImgs.filter(w => w.works_id === this.works_id )
return worksImgs
}
}
</script>
我将代码交叉发布在这里:
https://forum.vuejs.org/t/filter-help-trying-to-get-specific-elements-of-array-using-filter/54597
答案 0 :(得分:0)
由于getWorksImgs()
返回一个数组,而不是对象,因此抛出了错误。
<div>
<img :src="getWorksImgs.mother">
</div>
由于与上述相同的原因,下一部分也将引发错误
<div v-for="(Img , index) in getWorksImgs.children" :key="index">
<img :src="Img">
</div>
您需要将for循环移到顶部div
<div class="deWorks" v-for="(o, i) in getWorksImgs" :key="i">
<div>
<img :src="o.mother">
</div>
<div v-for="(Img , index) in o.children" :key="index">
<img :src="Img">
</div>
</div>
答案 1 :(得分:0)
由于过滤器的原因,getWorkImgs()计算值将返回一个数组。
computed: {
getWorksImgs() {
return this.worksImgs.filter( w => w.works_id === this.works_id);
}
}
这应该有效:
<template>
<div class="wrapper">
<div class="deWorks" v-for="(o, i) in getWorksImgs" :key="i">
<div>
<img :src="o.mother">
</div>
<div v-for="(Img , index) in o.children" :key="index">
<img :src="Img">
</div>
</div>
</div>
</template>
<script>
import StoreWorks from '@/store/works'
export default {
data() {
return {
worksImgs: StoreWorks.images,
works_id: this.$route.params.works_id
}
},
computed: {
getWorksImgs() {
return this.worksImgs.filter( w => w.works_id === this.works_id);
}
}
};
</script>