【问题标题】:Return and set reversed value返回并设置反转值
【发布时间】:2018-07-21 09:41:58
【问题描述】:

我正在为表格创建排序逻辑。

我现在拥有的:

  • 可以单击表格标题对数据进行排序:
    <th @click="sort(sortParams.created_at)">Date</th>
  • 排序方法:

    sort(param) {
        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
            })
    }
    
  • 存储所有排序参数的对象:

    sortParams: {
        default: '-created_at',
        id: 'id',
        created_at: 'created_at',
    }  
    

我想要做的:通过axios成功获取数据后反向排序参数。
我的意思是如果它是sortParams.id = 'id',它可能会更改为sortParams.id = '-id'。
我做了一个可以处理这个的方法:

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

如何在sort() 中使用reverseSortParam()?我的意思是,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

【问题讨论】:

  • 你能分享这个现场小提琴/sn-p吗?
  • @C2486 我从来没有把 Vue 组件当作小提琴,但我会尝试做一些类似的事情,这可能会尽快重现我的问题。
  • 你不能制作.vue文件,而是直接用Vue.component,Something like this
  • 你也可以只使用codesandbox并实际使用.vue文件
  • @C2486 我已经更新了我的问题

标签: vue.js


【解决方案1】:

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

考虑更改以下内容:

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() 在这种情况下使用此排序参数

【讨论】:

  • 谢谢!我要实现,尤其是你的异步方法,我认为这是一个好方法。
猜你喜欢
  • 2021-04-19
  • 2019-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多