javascript - 在 vue.js 中按类型对评论进行排序

标签 javascript vue.js vuejs2

我有一个带有选择过滤器的组件表单:

 <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.typefilter type?当用户选择特定过滤器时,我需要对评论进行排序。在 v-for 中,我有 comment.type

最佳答案

一种解决方案是使用数据变量进行过滤器选择,并使用计算属性返回过滤后的评论:

  1. 在容器组件中创建一个数据变量来保存选定的过滤器类型(例如,filterType)。由于来自选择组件的 filter 事件发出事件数据中的过滤器 ID(通过 $event 在模板中可用),我们可以使用它来设置 filterType @filter-事件处理器:

    // template
    <filter-select @filter="filterType = $event" />
    
    // script
    data() {
      return {
        filterType: 0
      }
    }
    
  2. 创建 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)
            );
      }
    }
    
  3. 在您的 v-for 循环中引用该计算属性:

    <comment v-for="comment in comments" :key="comment.id" :data="comment" />
    

demo

关于javascript - 在 vue.js 中按类型对评论进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54564104/

相关文章:

javascript - ReferenceError : function is not defined. 在 Jasmine 单元测试中

javascript - Jquery 列表更新

javascript - Vue.js 中未定义组件 props

javascript - 使用 switch 语句更改图标图像

vue.js - 在路由更改时更新 VueJs 组件

javascript - highcharts-vue 给出有关 highcharts HTML 元素的错误

javascript - 使用 javascript(jquery) 从外部 SVG 文件获取或设置 css 类值

javascript - 无法对对象数组进行排序

vue.js - Vuetify 幻灯片组 @click ="toggle"

javascript - 如何以编程方式替换 @click 事件?