vue貨幣過濾器的實(shí)現(xiàn)方法
自定義事件也可以用來創(chuàng)建自定義的表單輸入組件,使用 v-model 來進(jìn)行數(shù)據(jù)雙向綁定。
所以要讓組件的 v-model 生效,它必須:
- 接受一個(gè) value 屬性
- 在有新的 value 時(shí)觸發(fā) 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)
}
}
})
效果圖如下:

每個(gè) Vue 實(shí)例都實(shí)現(xiàn)了事件接口(Events interface),即:
使用 $on(eventName) 監(jiān)聽事件
使用 $emit(eventName) 觸發(fā)事件
v-model實(shí)現(xiàn)雙向傳遞。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue實(shí)現(xiàn)的上傳圖片到數(shù)據(jù)庫并顯示到頁面功能示例
這篇文章主要介紹了vue實(shí)現(xiàn)的上傳圖片到數(shù)據(jù)庫并顯示到頁面功能,結(jié)合實(shí)例形式分析了基于vue.js的數(shù)據(jù)庫操作及頁面圖片顯示相關(guān)操作技巧,需要的朋友可以參考下2018-03-03
Vue通過字符串關(guān)鍵字符實(shí)現(xiàn)動(dòng)態(tài)渲染input輸入框
這篇文章主要為大家詳細(xì)介紹了Vue如何通過字符串關(guān)鍵字符實(shí)現(xiàn)動(dòng)態(tài)渲染input輸入框。文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-12-12
Vue 第三方字體圖標(biāo)引入 Font Awesome的方法
今天小編就為大家分享一篇Vue 第三方字體圖標(biāo)引入 Font Awesome的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-09-09
vue router動(dòng)態(tài)路由設(shè)置參數(shù)可選問題
這篇文章主要介紹了vue-router動(dòng)態(tài)路由設(shè)置參數(shù)可選,文中給大家提到了vue-router 動(dòng)態(tài)添加 路由的方法,需要的朋友可以參考下2019-08-08
vue-cli2.x舊版本卸載不掉的問題踩坑指南(附Vue腳手架安裝教程)
遇到一個(gè)Vuecli2腳手架卸載不了的問題,查了許多資料說的都比較復(fù)雜,所以下面這篇文章主要給大家介紹了關(guān)于vue-cli2.x舊版本卸載不掉的問題踩坑的相關(guān)資料,文中還附了Vue腳手架安裝教程,需要的朋友可以參考下2022-07-07
詳解Vue項(xiàng)目中出現(xiàn)Loading chunk {n} failed問題的解決方法
這篇文章主要介紹了詳解Vue項(xiàng)目中出現(xiàn)Loading chunk {n} failed問題的解決方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-09-09

