【问题标题】:Adding a filter to Vue.js table using computed properties使用计算属性向 Vue.js 表添加过滤器
【发布时间】:2019-11-30 19:55:03
【问题描述】:

我有一个使用对象数组生成的表。我很难弄清楚如何使用计算属性来过滤对象数组。我正在使用 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
    }
  }
})

这是pen

【问题讨论】:

标签: javascript vue.js vuejs2


【解决方案1】:

计算属性必须返回一个值,你可以像使用数据和道具一样使用它。所以你需要做的是返回过滤器的结果。对于没有search 选项的情况,您可以返回不带过滤器的原始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">

【讨论】:

  • 我进行了更改,但没有任何反应。 codepen.io/isogunro/pen/bGGrWZG?editors=1011
  • 它看起来工作正常。当您在搜索框中输入NO 时,表格只显示NO 作为funding 的值的数据。
  • 哦...我期待逐步搜索...所以如果我输入N,我会看到以N 开头的任何内容
猜你喜欢
  • 2019-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
相关资源
最近更新 更多