Select Vue Filter Based on Variable

What i have

I am creating a table based on a 2D array in Vue2. I can get the table to display everything with all the values ​​in the right places, but I'm having formatting issues. The template looks something like this:

<table>
  <thead>
    <tr>
      <th>Title</th>
      <th>Column 1</th>
      <th>Column 2</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="row in data">
      <td>{{row[0]}}</td>
      <td>{{row[3]+row[1]+row[4]}}</td>
      <td>{{row[3]+row[2]+row[4]}}</td>
    </tr>
  </tbody>
</table>

And the data looks something like this:

var data = [
  ['revenue', 123.4, 153.48, '$'],
  ['cost', 93.26, 109.48, '$'],
  ['profit', 30.14, 44, '$'],
  ['margin', 24.425, 28.668, '', '%']
];

What i worked

It works ... ish. I can have any lines that I want, and I can specify units - a prefix or suffix - but this is not ideal. The biggest problem is that the currency has a different number of decimal places. I could store these values ​​as strings, but some of them are reused in the calculations, which means I have to parse them.

What i tried

. , , , , , . {{row[1] | currency}}, . , . revenue, cost profit - , margin - .

4- :

var data = [
  ['revenue', 123.4, 153.48, 'currency'],
  ['cost', 93.26, 109.48, 'currency'],
  ['profit', 30.14, 44, 'currency'],
  ['margin', 24.425, 28.668, 'percent']
];

- , :

<td>{{row[1] | row[3]}}</td>
<td>{{row[2] | row[3]}}</td>

. filters[row[3]] , , . , , , - this.formatters[row[3]](row[1]), , . , , , .

. . , , .

+4
3

.

new Vue({
  el:"#app",
  data:{
    data: [
      ['revenue', 123.4, 153.48, "currency"],
      ['cost', 93.26, 109.48, "currency"],
      ['profit', 30.14, 44, "currency"],
      ['margin', 24.425, 28.668,  "percent"]
    ]
  },
  methods:{
    format(value, filter){
      return Vue.filter(filter)(value)
    }
  }
})

  <tr v-for="row in data">
    <td>{{row[0]}}</td>
    <td>{{format(row[1], row[3])}}</td>
    <td>{{format(row[1], row[3])}}</td>
  </tr>

.

+2

Vue , , -, , .

- , .

, - :

filters: {
  format(value, type) {
    return this.formatters[type](value);
  }
}

:

<td>{{row[2] | format(row[3]) }}</td>
+1

{{row[2] | rowFilter(row[3])}} 

-3

Source: https://habr.com/ru/post/1675636/


All Articles