网络编程
位置:首页>> 网络编程>> JavaScript>> vue货币过滤器的实现方法

vue货币过滤器的实现方法

作者:CURRY_zhao  发布时间:2024-05-09 10:40:58 

标签:vue,过滤器

自定义事件也可以用来创建自定义的表单输入组件,使用 v-model 来进行数据双向绑定。

所以要让组件的 v-model 生效,它必须:

  • 接受一个 value 属性

  • 在有新的 value 时触发 input 事件

代码如下:

HTML:


<div id="app">
<p>{{ message }}</p>

<currency-input label="Price" v-model="price"></currency-input>
<currency-input label="Shipping" v-model="shipping"></currency-input>
<currency-input label="Handling" v-model="handling"></currency-input>
<currency-input label="Discount" v-model="discount"></currency-input>
<p>Total: ${{ total }}</p>
</div>

JavaScript:


Vue.component('currency-input', {
template: `\
<div>\
 <label v-if="label">{{ label }}</label>\
  $\
  <input\
  ref="input"\
   v-bind:value="value"\
   v-on:input="updateValue($event.target.value)"\
   v-on:focus="selectAll"\
   v-on:blur="formatValue"\
   >\
  </div>\
`,
props: {
value: {
 type: Number,
  default: 0
 },
 label: {
 type: String,
  default: ''
 }
},
mounted: function () {
this.formatValue()
},
methods: {
 updateValue: function (value) {
 var result = currencyValidator.parse(value, this.value)
  if (result.warning) {
  this.$refs.input.value = result.value
  }
  this.$emit('input', result.value)
 },
 formatValue: function () {
 this.$refs.input.value = currencyValidator.format(this.value)
 },
 selectAll: function (event) {
 setTimeout(function () {
  event.target.select()
  }, 0)
 }
}
})
new Vue({
el: '#app',
data: {
 message: 'Hello Vue.js!',
 price: 0,
 shipping: 0,
 handling: 0,
 discount: 0
},
computed: {
total: function () {
 return ((
  this.price * 100 +
   this.shipping * 100 +
   this.handling * 100 -
   this.discount * 10
  ) / 100).toFixed(2)
 }
}
})

效果图如下:

vue货币过滤器的实现方法

每个 Vue 实例都实现了事件接口(Events interface),即:

使用 $on(eventName) 监听事件
使用 $emit(eventName) 触发事件

v-model实现双向传递。

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com