vue js 2 сортировка таблицы - PullRequest
0 голосов
/ 16 мая 2018

У меня есть 2 вопроса с vue.js 2 и скрипкой здесь: https://jsfiddle.net/tmun9cxa/1/

  1. Когда вы щелкаете заголовок столбца, почему моя сортировка не работает?Какое решение?

  2. Как мне сделать так, чтобы поле ввода поиска осуществляло поиск только по столбцу pn?

Множество примеровя обнаружил, что использую vue1 и устарел.

<input type="text" value="" v-model="search" placeholder="Search">

<table style="text-align: center;">
    <thead>
        <tr>
            <th v-for="column in columns">
                <a 
                    href="#"
                    v-on:click="sort(column.shortcode)">{{column.label}}
                </a>
            </th>
        </tr>
    </thead>
    <tbody>
        <tr v-for="(product) in products">
            <td>{{product.pn}}</td>
            <td>{{product.od}}</td>
            <td>{{product.id}}</td>
            <td>{{product.thickness}}</td>
            <td>{{product.lo}}</td>
            <td>{{product.weight}}</td>
        </tr>
    </tbody>
</table>

JavaScript здесь

var vm = new Vue({
        el: '#app',
        data: {
            currentSort: 'pn',
            currentSortDir: 'asc',
            search: '',
            columns: [
                { label: 'P/N', shortcode: 'pn' },
                { label: 'OD (De,mm)', shortcode: 'od' },
                { label: 'ID (De,mm)', shortcode: 'id' },
                { label: 'Thickness (De,mm)', shortcode: 'thickness' },
                { label: 'LO', shortcode: 'lo' },
                { label: 'Weight (kg/1000)', shortcode: 'weight' },
            ], // columns
            products: [
                { 
                    pn: 170158,
                    od: 13,
                    id: .44,
                    thickness: 1,
                    lo: .45,
                    weight: .7
                },{ 
                    pn: 1803561,
                    od: 12,
                    id: .8,
                    thickness: .7,
                    lo: .11,
                    weight: .5
                },{ 
                    pn: 170149,
                    od: 9,
                    id: .64,
                    thickness: .6,
                    lo: .75,
                    weight: .3
                },{ 
                    pn: 150149,
                    od: 15,
                    id: .22,
                    thickness: .3,
                    lo: .55,
                    weight: .9
                },
            ], // products
        },
        methods: {
            sort:function(col) {
                //console.log( 'current: '+this.currentSort );
                //console.log( 'col: '+col );
                //var colthing = col;

                // if you click the same label twice
                if(this.currentSort == col){
                    console.log( 'same col: '+col );
                    // sort by asc
                    this.products = this.products.sort((a, b) => {
                        return a.col >= b.col;
                    });
                }else{
                    this.currentSort = col;
                    console.log( 'diff col: '+col );
                    // sort by desc
                    this.products = this.products.sort((a, b) => {
                        return a.col <= b.col;
                    });
                } // end if

            }, // sort

        }, // methods
    }); // vue

1 Ответ

0 голосов
/ 16 мая 2018

сортировка столбцов, как указано, не работала, потому что вам нужно использовать a[col] вместо a.col

Кроме того, вам следует рассмотреть возможность использования вычисленного значения вместо изменения исходных данных. Это также упрощает фильтрацию.

вот обновленный скрипт (обратите внимание, что <tr v-for="(product) in products"> должно быть <tr v-for="(product) in showProducts">, чтобы это работало)

var vm = new Vue({
  el: '#app',
  data: {
    currentSort: 'pn',
    currentSortDir: 'asc',
    search: '',
    columns: [
      { label: 'P/N', shortcode: 'pn' },
      /// more columns ...
    ], // columns
    products: [
      //.... objects
    ], // products
  },
  computed: {
    showProducts() {
      return this.products.filter(a => {
        console.log(a.pn)
        return (a.pn + '').includes(this.search)
      })
        .sort((a, b) => {
        if (this.currentSortDir === 'asc') {
	        return a[this.currentSort] >= b[this.currentSort];      
        }
        return a[this.currentSort] <= b[this.currentSort];
      })
    },
  },
  methods: {
    sort:function(col) {
      // if you click the same label twice
      if(this.currentSort == col){
        this.currentSortDir = this.currentSortDir === 'asc' ? 'desc' : 'asc';
      }else{
        this.currentSort = col;
        console.log( 'diff col: '+col );
      } // end if

    }, // sort

  }, // methods
}); // vue

наконец, скрипка: https://jsfiddle.net/tmun9cxa/2/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...