首页 > 解决方案 > 使用计算属性向 Vue.js 表添加过滤器

问题描述

我有一个使用对象数组生成的表。我很难弄清楚如何使用计算属性来过滤对象数组。我正在使用 Vue.js。我不确定如何在我的计算属性中正确使用 filter() 来过滤表。

new Vue({
  el:"#app",
  data: () => ({
    search:'',
    programs: [],
    editableKeys: ['date', 'company', 'funding', 'funded', 'recruit', 'program'],
  }),
  created () {
    this.getPrograms();
  },
  methods: {
    getPrograms() {
     axios.get("https://my-json-server.typicode.com/isogunro/jsondb/Programs").then(response => {
       this.programs = response.data.map(program => ({
           ...program,
           isReadOnly: true,
            dropDowns: ["Apple","Google"]
       }));
      }).catch(error => {
       console.log(error);
      });
    },
    editItem (program) {
      program.isReadOnly = false
    },
    saveItem (program) {
      program.isReadOnly = true
      console.log(program)
      alert("New Value: "+program.company)
      alert("Previous Value: "+program.company)
    },
    bgColor (program) {
      return program.funded === program.funding ? 'yellow' : 'white'
    },
    formatDate(program){
      var formatL = moment.localeData().longDateFormat('L');
      var format2digitYear = formatL.replace(/YYYY/g,'YY');
      return moment(program.Date).format(format2digitYear);
    },
    updateField(program){
      console.log(program)
      alert(program)
    }
  },
  computed: {
    searchContents(){
      this.programs.filter(this.search === )//??? not sure how to filter correctly
    }
  }
})

这是

标签: javascriptvue.jsvuejs2

解决方案


计算属性必须返回一个值,您可以像使用数据和道具一样使用它。所以你需要做的是返回过滤器的结果。对于没有选项的情况,您可以在没有过滤器的情况下search返回 raw 。programs

计算的属性将是这样的:(如果您按其funding属性过滤程序。)

computed: {
  searchContents(){
    if (this.search === '') {
      return this.programs
    }

    return this.programs.filter(x => this.search === x.funding)
  }
}

然后您可以在以下位置使用该计算属性v-for

  <tr v-for="(program, index) in searchContents">

推荐阅读