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

标签 javascript wordpress woocommerce vue.js

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

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

我的代码是这样的:

<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>

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

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

  1. 如果我传递 this.formatVariations(this.variationOrders) 和 console.log,我得到 undefined

  2. 如果我传递 this.formatVariations(variationOrders) 和 console.log,我会得到 [Vue warn]: Error in data(): "ReferenceError: variationOrders is not defined"

我怀疑在函数被调用时,那个变量还不存在。

有什么我想念的吗?

更新 1

我已将代码更新为以下内容。我更近了,但不幸的是, View 没有更新。

我的代码是这样的:

<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>

更新 2

formatVariations() 函数返回一个样本集,如下所示:

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 />

更新 3

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

:
customer_name
:
(...)
order_id
:
(...)
product_name
:
(...)
qty
:
(...)
store_id
:
(...)
variation
:
"[{"id": 35, "key": "choose-your-cake", "value": "Naked"}, {"id": 36, "key": "choose-sugar", "value": "Yes"}]"

最佳答案

self.variationOrders 在数据方法中未定义; self 仅在 getTotals 方法的范围内可用。

相反,使用 computed property格式化

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
    })
  }
}

并在模板中使用计算属性。

<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"}]'
  },
]

关于javascript - 在传递给 Vue Good-Table 之前格式化列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46709142/

相关文章:

javascript - 将 javascript 放在 html5 的外部文件中

javascript - 复杂的异步流程未能按预期执行

php - 从 WooCommerce 优惠券中排除具有特定属性术语的产品

javascript设置对象相等

javascript - 作为函数的变量

php - 在重力表单中,表单在成功提交后消失

javascript - 需要更改 wordpress 的字体选项

php - SQL 和 WordPress : Extract two custom fields with SQL

php - Woocommerce:根据用户输入定制价格

php - WooCommerce:如何以编程方式将多个产品添加到购物车?