Home > Software design >  How can I display a default value if the expected value is null?
How can I display a default value if the expected value is null?

Time:05-06

Is there away to display a default value if the expected value is null?

Ex.

<v-card-subtitle >{{ user.name??'n/a' }}</v-card-subtitle>

CodePudding user response:

Maybe with computed property:

new Vue({
  el: "#demo",
  data() {
    return { text: null }
  },
  computed: {
    textVal() {
      return this.text || 'n/a'
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <p> {{ textVal }} </p>
</div>

CodePudding user response:

If you really want it in the template, you could use

<v-card-subtitle >{{ user.name || 'n/a' }}</v-card-subtitle>

But I do heavily recommend using it in the script section, will give you more flexibility and keep the template simple and clean.

CodePudding user response:

In case you have several items that might need 'n/a', you could try this

<v-card-subtitle >{{ user.name | handleEmptyValue }}</v-card-subtitle>

<script>
import _ from "lodash";

export default {
  filters: {
    handleEmptyValue(value) {
      return _.isEmpty(value) ? "N/A" : value;
    }
  }
};
</script>
  • Related