在传递给Vue Good-Table之前格式化列数据

时间:2017-10-12 12:03:36

标签: javascript wordpress woocommerce vue.js

我已经构建了一个Vue.js组件,该组件从Woocommerce商店获取订单。这些订单包含产品的产品差异,并作为对象接收。

在表格中,我需要在对象显示之前对其进行格式化。

我的代码如下所示:

err := C.Find(bson.M{"Receiver": userId}).Sort("_id":-1).All(&result)

Variations 列中,我传递了一个负责格式化字符串的函数。函数本身工作正常,但我无法将接收到的对象从API传递给此函数。

我在控制台中收到以下错误消息:

  1. 如果我通过<template> <div> <vue-good-table title="" :columns="columns" :rows="variationOrders" :paginate="true" :lineNumbers="true"/> </div> </template> <script> export default { data: function() { return { variationOrders: [], columns: [ { label: 'Order#', field: 'order_id', filterable: true, }, { label: 'Customer', field: 'customer_name', //type: 'number', html: false, filterable: true, }, { label: 'QTY', field: 'qty', type: 'number', //inputFormat: 'YYYYMMDD', //outputFormat: 'MMM Do YY', }, { label: 'Product', field: 'product_name', //type: 'percentage', html: false, }, { label: 'Variations', field: this.formatVariations(self.variationOrders), //type: 'percentage', html: true, }, { label: 'Timeslot', field: 'timeslot', //type: 'percentage', html: false, }, { label: 'Transportation', field: 'store_id', //type: 'percentage', html: false, }, ], } }, methods: { getTotals: function() { var self = this; var productId = document.getElementById('product-id').getAttribute('data-id'); axios.get('/api/v1/order_variations/' + productId) .then(function (response) { self.variationOrders = response.data.order_variations; //console.log(response.data); }) .catch(function(error) { // }); }, formatVariations: function(variationOrders) { console.log(variationOrders); }, }, mounted: function() { this.getTotals(); // call the API every 30 seconds to fetch new orders setInterval(function () { this.getTotals(); }.bind(this), 5000); } } </script> 和console.log,我会this.formatVariations(this.variationOrders)

  2. 如果我通过undefined和console.log,我会this.formatVariations(variationOrders)

  3. 我怀疑在调用该函数时,该变量尚不存在。

    有什么我想念的吗?

    更新1

    我已将代码更新为以下内容。我很接近但不幸的是视图没有更新。

    我的代码如下:

    [Vue warn]: Error in data(): "ReferenceError: variationOrders is not defined"

    更新2

    formatVariations()函数返回如下样本集:

    <template>
    <div>
    
        <vue-good-table
          title=""
          :columns="formattedColumns"
          :rows="variationOrders"
          :paginate="true"
          :lineNumbers="true"/>
    
    </div>
    </template>
    
    <script>
        export default {
            data: function() {
                return {
                    variationOrders: [],
                    columns: [
                    {
                      label: 'Order#',
                      field: 'order_id',
                      filterable: true,
                    },
                    {
                      label: 'Customer',
                      field: 'customer_name',
                      //type: 'number',
                      html: false,
                      filterable: true,
                    },
                    {
                      label: 'QTY',
                      field: 'qty',
                      type: 'number',
                      //inputFormat: 'YYYYMMDD',
                      //outputFormat: 'MMM Do YY',
                    },
                    {
                      label: 'Product',
                      field: 'product_name',
                      //type: 'percentage',
                      html: false,
                    },
                    {
                      label: 'Variations',
                      field: 'variation',
                      //type: 'percentage',
                      html: true,
                    },
                    {
                      label: 'Timeslot',
                      field: 'timeslot',
                      //type: 'percentage',
                      html: false,
                    },
                    {
                      label: 'Transportation',
                      field: 'store_id',
                      //type: 'percentage',
                      html: false,
                    },
                  ],
                }
            },
            methods: {
                getTotals: function() {
                    var self = this;
                    var productId = document.getElementById('product-id').getAttribute('data-id');
                    axios.get('/api/v1/order_variations/' + productId)
                    .then(function (response) {
                        self.variationOrders = response.data.order_variations;
                    })
                    .catch(function(error) {
                        //
                    });
                },
                formatVariations: function(variationOrders) {
                  var variationsString = '';
                  variationOrders.forEach(function(item) {
                    var variations = JSON.parse(item.variation);
                    for(var i = 0; i < variations.length; i++) {
                      variationsString = variationsString + variations[i].key + ': ' + variations[i].value + '<br />';
                    }
                  });
                  return variationsString;
                },
            },
            computed: {
              formattedColumns(){
                const formattedVariations = this.formatVariations(this.variationOrders);
                console.log(formattedVariations);
                return this.columns.map(c => {
                  if (c.label == "Variations") {
                    return {label: "Variations", field: formattedVariations , html: true}
                  }
                  return c;
                })
              }
            },
            mounted: function() {
                this.getTotals();
                // call the API every 30 seconds to fetch new orders
                setInterval(function () {
                    this.getTotals();
                }.bind(this), 5000); 
            },
        }
    </script>
    

    更新3

    这是API返回的一个数组项:

    choose-your-cake: Naked<br />choose-sugar: Yes<br />choose-your-cake: Naked<br />choose-sugar: No<br />choose-your-cake: Naked<br />choose-sugar: No<br />choose-your-cake: Naked<br />choose-sugar: Yes<br />choose-your-cake: Naked<br />choose-sugar: Yes<br />choose-your-cake: Coated<br />choose-sugar: No<br />choose-your-cake: Naked<br />choose-sugar: Yes<br />choose-your-cake: Naked<br />choose-sugar: Yes<br />choose-your-cake: Coated<br />choose-sugar: Yes<br />choose-your-cake: Naked<br />choose-sugar: Yes<br />choose-your-cake: Naked<br />choose-sugar: Yes<br />choose-your-cake: Naked<br />choose-sugar: Yes<br />
    

1 个答案:

答案 0 :(得分:5)

self.variationOrders在数据方法中未定义; self仅适用于getTotals方法。

相反,请使用computed property格式化columns

computed:{
  formattedColumns(){
    const formattedVariations = this.formatVariations(this.variationOrders)
    return this.columns.map(c => {
      if (c.label === "Variations")
        return {label: "Variations", field: formattedVariations , html: true}

      return c
    })
  }
}

并在模板中使用computed属性。

<vue-good-table
  title=""
  :columns="formattedColumns"
  :rows="variationOrders"
  :paginate="true"
  :lineNumbers="true"/>

每当variationOrders更改时,都应更新计算属性。

修改

上面回答了被问到的问题,但实际上没有呈现所需的表格(据我所知)。这是因为对vue-good-table的工作方式存在误解。

如果我理解正确,OP真正想要的是用HTML格式化表格中单元格的内容。为此,您只需使用范围内的插槽table-row。以下是模板的外观(本示例中的列是缩写的。)

<vue-good-table
  title=""
  :columns="columns"
  :rows="variationOrders"
  :paginate="true"
  :lineNumbers="true">
  <template slot="table-row" scope="props">
    <td>{{ props.row.order_id }}</td>
    <td>{{ props.row.customer_name }}</td>
    <td><span v-html="formatVariations(props.row.variation)"></span></td>
  </template>
</vue-good-table>

我还更新了formatVariations方法:

formatVariations: function(variationOrders) {
  let parsed = JSON.parse(variationOrders).map(order => {
    return `${order.key} : ${order.value} <br>`
  })
  return parsed.join('');
},

这假设数据格式如下:

[
  {
    order_id: 1,
    customer_name: "Bob NewHart",
    qty: 10,
    product_name: "Hats",
    variation: '[{"id": 35, "key": "choose-your-cake", "value": "Naked"}, {"id": 36, "key": "choose-sugar", "value": "Yes"}]'
  },
  {
    order_id: 2,
    customer_name: "Mary Lamb",
    qty: 10,
    product_name: "Necklaces",
    variation: '[{"id": 35, "key": "choose-your-cake", "value": "Naked"}, {"id": 36, "key": "choose-sugar", "value": "Yes"}]'
  },
]