You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 04:48:03