带有 jQuery autoNumeric 或数字插件的 Vuejs - 仅格式化列表 (v-for) 中的数据

Vuejs with jQuery autoNumeric or number plugin - only data in list (v-for) are formatted

在过去的 48 小时里,我一直在尝试解决这个问题,但仍然没有成功。我正在使用 jquery autoNumeric/numeric 插件来格式化数字,因此它是逗号分隔的。我一直在单独使用 jQuery 进行此操作,并且运行良好。我是 Vue 的新手,所以当我将它与 Vue 一起使用时,我在 **update() ** 函数中对其进行初始化后开始工作。但是发生了一些事情,我有以下模型: {'success':1,totalIncome:49000,data:{[{'name':'john','income':'200'},{'name':'Sam','income':'500'}]}

还有我的html:

<div id="app">
     <span v-for="item in model.data">{{item.income}}</span>
     <span>{{model.totalIncome}}</span>
</div>

并且在更新挂钩内的 vue root 实例中,我将 autoNumeric 初始化为:

Updated:function() {
      $('span'). autoNumeric('init') ;
} 

但从结果来看,只有 span 标记在 v-for 指令中被格式化,其他 span 标签不是。我需要帮助。我究竟做错了什么?

更新

对于输出使用过滤器。 vue2-filters 让一切变得简单

进口:

import Vue from 'vue'
import Vue2Filters from 'vue2-filters'

Vue.use(Vue2Filters)

用法:

{{ amount | currency }} // 12345 => ,345.00

使用不同的符号:

{{ amount | currency('£') }} // 12345 => £12,345.00

使用不同的数字小数位:

{{ amount | currency('₽', 0) }} // 12345 => ₽12,345

混合使用 jquery 和 vue 的问题在于它们可能会互相争斗以更新组件。考虑尽可能多地坚持使用 Vue。

相反,使用以下插件的 vue 版本: https://github.com/autoNumeric/vue-autoNumeric

首先,不要使用自动数字输出。它的主要目的是格式化输入,而不是输出。它有点过时了。 vue-autonumeric 也用于输入。不要使用它们。

要格式化输出,请使用 accounting.js (http://openexchangerates.github.io/accounting.js/)。对于您的目的来说,这是更好的选择。它是实际的、微小的、独立的库。并且不要使用更新的钩子,而是使用过滤器。

定义:

// This is global filter for all components,
// but you can define filters in components also
Vue.filter('euroFormat', function (value) {
  if (!value) return ''
  return accounting.formatMoney(value, "€", 2, ".", ",")
})

用法:

<!-- Min version from CDN -->
<script src="https://unpkg.com/accounting@0.4.1/accounting.min.js"></script>

<div id="app">
  <span v-for="item in model.data>
    {{ item.income | euroFormat }}
  </span>
  {{ model.totalIncome | euroFormat }}
</div>

完成。就这么简单

PS:如果您需要在键入时格式化输入值,也很简单:

new Vue({
  el: '#app',
  data: {
    income: ''
  },
  filters: {
    formatted (value) {
      if (!value) return ''
      return accounting.formatMoney(value, "€", 2, ".", ",")
    }
  }
})
[v-cloak] {
  display: none;
}
<div id="app">
  <input v-model="income">
  <p>Your income is <span v-cloak>{{ income | formatted }}</span></p>
</div>

<script src="https://unpkg.com/vue@2.5.3/dist/vue.min.js"></script>
<script src="https://unpkg.com/accounting@0.4.1/accounting.min.js"></script>