在 Vue.js 2.0 中实现 v-model 格式的正确方法是什么 [英] What's the proper way to implement formatting on v-model in Vue.js 2.0

查看:63
本文介绍了在 Vue.js 2.0 中实现 v-model 格式的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举个简单的例子:输入货币数据的文本框.要求以$1,234,567"格式显示用户输入并去除小数点.

For a simple example: textbox to input currency data. The requirement is to display user input in "$1,234,567" format and remove decimal point.

我尝试过 vue 指令.由于其他控件刷新 UI 时,不会调用指令的 update 方法.所以文本框中的值会恢复为没有任何格式的值.

I have tried vue directive. directive's update method is not called when UI is refreshed due to other controls. so value in textbox reverts to the one without any formatting.

我也尝试过 v-on:change 事件处理程序.但我不知道如何在事件处理程序中调用全局函数.在每个 Vue 对象中都创建货币转换方法不是一个好习惯.

I also tried v-on:change event handler. But I don't know how to call a global function in event handler. It is not a good practice to create a currency convert method in every Vue object.

那么现在 Vue 2.0 中的标准格式化方式是什么?

So what is the standard way of formatting in Vue 2.0 now?

问候

推荐答案

请检查这个有效的 jsFiddle 示例:https://jsfiddle.net/mani04/bgzhw68m/

Please check this working jsFiddle example: https://jsfiddle.net/mani04/bgzhw68m/

在这个例子中,格式化的货币输入本身就是一个组件,它像 Vue.js 中的任何其他表单元素一样使用 v-model.您可以按如下方式初始化此组件:

In this example, the formatted currency input is a component in itself, that uses v-model just like any other form element in Vue.js. You can initialize this component as follows:

<my-currency-input v-model="price"></my-currency-input>

my-currency-input 是一个独立的组件,用于在输入框非活动时格式化货币值.当用户将光标放在里面时,格式被删除,以便用户可以轻松地修改值.

my-currency-input is a self-contained component that formats the currency value when the input box is inactive. When user puts cursor inside, the formatting is removed so that user can modify the value comfortably.

这是它的工作原理:

my-currency-input 组件有一个计算值 - displayValue,它有 getset定义的方法.在 get 方法中,如果输入框未激活,则返回格式化的货币值.

The my-currency-input component has a computed value - displayValue, which has get and set methods defined. In the get method, if input box is not active, it returns formatted currency value.

当用户输入输入框时,displayValue计算属性的set方法使用$emit发出值,从而通知父组件关于这个变化.

When user types into the input box, the set method of displayValue computed property emits the value using $emit, thus notifying parent component about this change.

在自定义组件上使用 v-model 的参考:https://vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events

Reference for using v-model on custom components: https://vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events

这篇关于在 Vue.js 2.0 中实现 v-model 格式的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆