首页 > 解决方案 > 返回并设置反转值

问题描述

我正在为表格进行排序逻辑。

我现在拥有的:

我想要做的:通过axios.
我的意思是,如果是sortParams.id = 'id',它可能会更改为sortParams.id = '-id'
我做了一个可以处理这个的方法:

reverseSortParam(param) {
    if (param.charAt(0) === '-') {
        return param.replace('-', '')
    }
    return '-' + param
}

我如何reverseSortParam()在里面使用sort()?我的意思是,sort()只接受字符串值,我需要以reverseSortParam()某种方式传递字符串值的来源。


UPD:一些可能有用的狗屎代码,但在我的项目中没有它的位置:

<th @click="sort(sortParams.created_at, 'created_at')">Date</th>`

sort(param, paramName) {
    let that = this
    axios.get(process.env.API_BASE_URL + process.env.API_BASE_VERSION + 'data?sort=' + param + '&page=' + that.tableData.current_page)
        .then(function (response) {
            that.tableData = response.data
            that.sortParams[paramName] = that.reverseSortParam(param)
        })
}

JSFiddle

标签: vue.js

解决方案


我认为你过度设计了这个。您保留了一个潜在的未来排序参数表,但不是当前状态。您还想根据一个值更改此表。最重要的是,您目前只能对单个属性进行排序,但保持(以前的)排序状态,从而为使用它的用户带来有效的随机行为。

考虑更改以下内容:

data () {
  return {
    // Maps local names to api names
    sortMap: {
      created_at: 'created_at',
      time: 'datetime',
      id: 'id'
    },

    // The default sort
    sortParam: 'created_at'
  },

  methods: {
    async sort (localName) {
      // Figure out if we need to inverse the current sort
      const currentSort = this.sortParam.replace('-', '');

      // Set the current sort
      if (currentSort === this.sortMap[localName]) {
        this.sortParam = `-${this.sortParam}`.replace('--', '');
      } else {
        this.sortParam = this.sortMap[localName];
      }

      this.getData()
    },

    async getData () {
      // You probably want to factor out the api calls to their own file anyway
      this.tableData = await axios.get(..).data
    }
  }
}

现在,您无需将逻辑分散在各处,只需sort('created_at')从模板中调用即可。该方法确保我们使用正确的排序参数,getData()在这种情况下使用这个排序参数


推荐阅读