【问题标题】:Update a computed method from a function Vue从函数 Vue 更新计算方法
【发布时间】:2019-01-01 18:46:01
【问题描述】:

我在 VUE 中有一个排序和分页计算函数,它允许在表格中显示

sortedTransactions: function() {
      return this.transactions
          .sort((a, b) => {
            let modifier = 1;
            if (this.currentSortDir === "desc") modifier = -1;
            if (a[this.currentSort] < b[this.currentSort]) return -1 * modifier;
            if (a[this.currentSort] > b[this.currentSort]) return 1 * modifier;
            return 0;
          })
          .filter((row, index) => {
            let start = (this.currentPage - 1) * this.pageSize;
            let end = this.currentPage * this.pageSize;
            if (index >= start && index < end) return true;
          });
      }

所以我希望能够搜索数据,然后根据用户输入显示结果

searchResults() {
      const search = this.sortedTransactions.filter(transaction => { 
          return transaction.user_id.toLowerCase() === this.searchTable
        });
        this.sortedTransactions = search;
    }

当然,我需要在数据表中更新搜索结果,但看不到方法。

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    您应该修改数据属性 transactions 而不是更新计算属性,因为您正在做的事情不正确 this.sortedTransactions = search; 因为计算属性不是可变的,所以您的函数应该是这样的:

      searchResults() {
      const search = this.transactions.filter(transaction => { 
          return transaction.user_id.toLowerCase() === this.searchTable
        });
        this.transactions = search;
    }
    

    computed 属性 sortedTransactions 将自动更新

    【讨论】:

    • 完美,我应该看到的!
    【解决方案2】:

    在你的方法中定义 serchResults(),监听 @key 事件,并将它传递给方法来过滤结果。

    【讨论】:

      猜你喜欢
      • 2021-07-04
      • 1970-01-01
      • 2019-09-02
      • 2018-02-18
      • 2019-06-16
      • 2019-10-03
      • 1970-01-01
      • 1970-01-01
      • 2021-05-24
      相关资源
      最近更新 更多