vue实现数字资源
Vue 实现数字资源的常见方法
使用计算属性动态处理数字
export default {
data() {
return {
rawNumber: 1000
}
},
computed: {
formattedNumber() {
return this.rawNumber.toLocaleString()
}
}
}
模板中使用计算属性显示格式化数字:
<p>{{ formattedNumber }}</p>
自定义过滤器格式化数字
Vue.filter('formatNumber', function(value) {
if (!value) return ''
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
})
在模板中使用过滤器:
<p>{{ number | formatNumber }}</p>
使用第三方库处理复杂数字格式
安装 numeral.js:
npm install numeral
在组件中使用:
import numeral from 'numeral'
export default {
methods: {
formatCurrency(value) {
return numeral(value).format('$0,0.00')
}
}
}
数字动画效果实现
安装 vue-number-animation:
npm install vue-number-animation
使用示例:

<vue-number-animation
:from="0"
:to="1000"
:duration="2"
easing="easeOutQuad"
/>
数字输入组件实现
<template>
<input
type="text"
v-model="displayValue"
@blur="handleBlur"
@focus="handleFocus"
>
</template>
<script>
export default {
props: ['value'],
data() {
return {
displayValue: this.value
}
},
methods: {
handleFocus() {
this.displayValue = this.value
},
handleBlur() {
this.$emit('input', parseFloat(this.displayValue))
}
}
}
</script>
数字验证实现
export default {
methods: {
validateNumber(value) {
const regex = /^[0-9]+(\.[0-9]{1,2})?$/
return regex.test(value)
}
}
}
数字范围滑块组件
<template>
<div>
<input
type="range"
:min="min"
:max="max"
v-model="currentValue"
>
<span>{{ currentValue }}</span>
</div>
</template>
<script>
export default {
props: {
min: { type: Number, default: 0 },
max: { type: Number, default: 100 },
value: { type: Number, default: 50 }
},
data() {
return {
currentValue: this.value
}
},
watch: {
currentValue(newVal) {
this.$emit('input', newVal)
}
}
}
</script>






