一、不使用vue/cli腳手架搭建
1、該組件基於vue,element,accountingjs
2、引入相應的js文件
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> <script src="https://cdn.bootcss.com/accounting.js/0.4.1/accounting.js"></script> <!-- 引入樣式 --> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <!-- 引入組件庫 --> <script src="https://unpkg.com/element-ui/lib/index.js"></script>
3、如何使用:html部分
<div id="app">
<div style="display:inline-block">
<currency-input v-model="price" :decimal="4" style="width:200px;" @blur="inputBlur"></currency-input>
<el-button type="primary" size="small" @click="submit">提交</el-button>
</div>
</div>
4、如何使用:js部分
<script>
Vue.component("currency-input", {
template: '\
<div class="el-input el-input--small">\
<input class="el-input__inner"\
v-bind:value="formatValue"\
ref="input"\
v-on:input="updatevalue($event.target.value)"\
v-on:blur="onBlur"\
v-on:focus="selectAll"/>\
</div>\
',
props: {
value: {
type: [String, Number],
default: 0,
desc: '數值'
},
symbol: {
type: String,
default: '',
desc: '貨幣標識符'
},
decimal: {
type: Number,
default: 2,
desc: '小數位'
}
},
data() {
return {
focused: false,
}
},
computed: {
formatValue() {
if (this.focused) {
return accounting.unformat(this.value);
} else {
return accounting.formatMoney(this.value, this.symbol, this.decimal);
}
}
},
methods: {
updatevalue(value) {
var formatvalue = accounting.unformat(value);
this.$emit("input", formatvalue)
},
onBlur() {
this.focused = false;
this.$emit("blur");
this.dispatch("ElFormItem", "el.form.blur", [this.value]);
},
selectAll(event) {
this.focused = true;
setTimeout(() => {
event.target.select()
}, 0)
},
dispatch(componentName, eventName, params) {
var parent = this.$parent || this.$root;
var name = parent.$options.componentName;
while (parent && (!name || name !== componentName)) {
parent = parent.$parent;
if (parent) {
name = parent.$options.componentName;
}
}
if (parent) {
parent.$emit.apply(parent, [eventName].concat(params));
}
}
},
})
new Vue({
el: "#app",
data() {
return {
price: ""
}
},
created() {
setTimeout(() => {
this.price = 1100;
}, 1000);
},
methods: {
submit() {
console.log(this.price)
},
inputBlur() {
console.log("觸發了自定義事件");
}
},
})
</script>

