如何在 vue.js 模板中显示空间而不是 undefined 和 null? [英] How to display space instead undefined and null in vue.js template?

查看:85
本文介绍了如何在 vue.js 模板中显示空间而不是 undefined 和 null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 Vue.js 模板

This is Vue.js template

<strong>{{userdata.phone}}</strong>

当 userdata.phone == null 或 userdata.phone == undefined 时,我想显示空间.例如

When userdata.phone == null or userdata.phone == undefined, I would like to show space. for example

<strong> {{ userdata.phone | !null | !undefined }} </strong>

有可能吗?在这种情况下怎么办?

Is it possible? And in this case how do that?

<strong>{{userdata.location.city + userdata.location.state + userdata.location.country }}</strong>

userdata.locationi.city,state,country 可以为 null 或未定义

userdata.locationi.city,state,country can be null or undefined

推荐答案

解决方案与有一个 常规 Javascript 中值的默认回退.

<strong>{{ userdata.phone || " " }}</strong>

相同的解决方案适用于多个回退.

The same solution works for multiple fallbacks.

<strong>{{ userdata.location.city || userdata.location.state || userdata.location.country || " " }}</strong>

或者,如果有,使用 计算属性 会很方便涉及更复杂的逻辑或当您想重用它时:

Alternatively, it can be handy to use a computed property for this if there's more complex logic involved or when you want to reuse it:

computed: {
  phone: function () {
    return this.userdata.phone || " ";
  }
}

如果您只针对支持的浏览器取消合并或使用为您转译它的构建步骤,这通常是可取的.

If you're only targeting browsers that support nullish coalescing or use a build step that transpiles it for you, that's usually preferable.

<strong>{{ userdata.phone ?? " " }}</strong>

这篇关于如何在 vue.js 模板中显示空间而不是 undefined 和 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆