我有一个带有选择过滤器的组件表单:
<template>
<div class="form-group">
<select name="" v-model="filterRev" @change="filterReviews(filterRev)" class="form-control" id="">
<option value="0">All comments</option>
<option value="1">Good Comments</option>
<option value="2">Standard Comments</option>
<option value="3">Badd comment</option>
</select>
</div>
</template>
<script>
export default {
data() {
filterRev: 0
},
methods: {
filterReviews(type) {
if(Number.isInteger(parseInt(type))) {
this.$emit('filter', type);
}
},
}
}
</script>
关于组件评论我有这个:
<div @filter="..." v-for="(comment, index) in items" :key="comment.id">
<comment :data="comment"></comment>
</div>
我如何检查 comment.type
和 filter type
?当用户选择特定过滤器时,我需要对评论进行排序。在 v-for
中,我有 comment.type
。
最佳答案
一种解决方案是使用数据变量进行过滤器选择,并使用计算属性返回过滤后的评论:
在容器组件中创建一个数据变量来保存选定的过滤器类型(例如,
filterType
)。由于来自选择组件的filter
事件发出事件数据中的过滤器 ID(通过$event
在模板中可用),我们可以使用它来设置filterType
@filter
-事件处理器:// template <filter-select @filter="filterType = $event" /> // script data() { return { filterType: 0 } }
创建 computed property在容器组件中返回与过滤器选择匹配的评论数据。这使用
Array.prototype.filter
在评论数据数组上(即本例中的items
)。computed: { comments() { return Number(this.filterType) === 0 ? this.items : this.items.filter( comment => Number(comment.type) === Number(this.filterType) ); } }
在您的
v-for
循环中引用该计算属性:<comment v-for="comment in comments" :key="comment.id" :data="comment" />
关于javascript - 在 vue.js 中按类型对评论进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54564104/