如何在Vue.js中使用methods方法为props传入的数值添加千位分隔符
解决方法
你只需在模板的插值表达式里直接调用已经定义好的thousandSeparator方法,将price作为参数传入即可生效。
具体修改代码
模板部分修改
找到原有价格渲染的代码行,替换为以下内容:
<h6 class="price">Rp. {{ thousandSeparator(price) }}</h6>
可选优化方案
- 补充props类型校验
因为thousandSeparator方法要求入参为数字类型,建议给props明确标注类型,避免传入非数字值时报错:props: { name: String, price: Number, description: String, image: String }, - 使用计算属性简化调用
如果需要在多个位置用到格式化后的价格,可以新增计算属性封装格式化逻辑,模板中直接调用计算属性即可:
模板中使用方式:// 和methods同级新增computed选项 computed: { formattedPrice(): string { return this.thousandSeparator(this.price) } }<h6 class="price">Rp. {{ formattedPrice }}</h6>
内容的提问来源于stack exchange,提问作者Erwin Ramadhan
相关产品推荐
相关产品推荐

