细节:双花括号({{ ... }})在Vue.js中的用法

问题:

为什么后端返回的是数字类型时, { { form.orderPrice }}可以拿到值展示, { { form.orderPrice || "-" }} 不可以?

接口返回数据:

<el-form-item label="订单金额:" prop="orderPrice"> {
   
   { form.orderPrice || "-" }} 元 {
   
   { form.orderPrice }} </el-form-item>

首先,了解一下双花括号({ { ... }})在Vue.js中的用法。双花括号是Vue.js的插值语法,用于将表达式的值渲染到模板中。在这种情况下,{ { form.orderPrice }}用于显示form对象中orderPrice属性的值。

回到问题,为什么 { { form.orderPrice }} 可以显示返回的数字类型值,而 { { form.orderPrice || "-" }} 不可以显示。

这是因为 form.orderPrice 是一个数字类型的值,而 || 运算符在JavaScript中的工作方式可能导致不同的结果。

在JavaScript中,|| 运算符表示逻辑或(OR)运算。当应用于两个操作数时,它返回第一个“真值”(可以转换为true的值),如果没有真值,则返回最后一个操作数。换句话说,它将返回第一个非空、非零、非假的值。

如果 form.orderPrice 是一个数字类型的值,并且该值为正数(大于0),那么它被视为一个真值。因此,form.orderPrice || "-" 的结果将是 form.orderPrice 的值,而不是 "-"。这解释了为什么在 { { form.orderPrice }} 中可以正确显示订单金额。

然而,如果 form.orderPrice 是一个数字类型的值,并且该值为0或为空(或未定义),它将被视为一个假值。在这种情况下,form.orderPrice || "-" 的结果将是 "-",这解释了为什么 { { form.orderPrice || "-" }} 不会显示正确的订单金额。

为了确保在 form.orderPrice 为假值时也能显示 "-",可以考虑使用三元表达式(ternary expression)来实现条件显示:

扫描二维码关注公众号,回复: 15895924 查看本文章
<el-form-item label="订单金额:" prop="orderPrice">
  {
   
   { form.orderPrice !== null ? form.orderPrice + ' 元' : '-' }}
</el-form-item>

在上述代码中,当 form.orderPrice 不为 null 时,将显示订单金额加上 ' 元',否则将显示 "-"。这样可以确保在 form.orderPrice 为假值时也能正确显示 "-"

猜你喜欢

转载自blog.csdn.net/coinisi_li/article/details/131664952