Home > database >  Show a default value when state.value is underfined | Vue.js 3
Show a default value when state.value is underfined | Vue.js 3

Time:12-23

I have this code below on a component in Vuejs 3. It works fine, no problem at all.

But I wanted to show something when there is no result from:

<td> {{ $store.state.output[0].address }} </td>

If the code above is undefined or it is not existed, it should show something like '-' instead of an error.

<template>
    <tbody >
        <tr >
            <th scope="row" > Origin </th>
            <td> {{ $store.state.output[0].address }} </td>
            <td> {{ $store.state.output[0].distance }} </td>
            <td> {{ $store.state.output[0].fuelCost }} </td>
        </tr>
        <tr>
            <th scope="row">1</th>
            <td> {{ $store.state.output[1].address }} </td>
            <td> {{ $store.state.output[1].distance }} </td>
            <td> {{ $store.state.output[1].fuelCost}} </td>
        </tr>
        <tr>
            <th scope="row">2</th>
            <td> {{ $store.state.output[2].address }} </td>
            <td> {{ $store.state.output[2].distance }} </td>
            <td> {{ $store.state.output[2].fuelCost }} </td>
        </tr>
        <tr>
            <th scope="row">3</th>
            <td> {{ $store.state.output[3].address }} </td>
            <td> {{ $store.state.output[3].distance }} </td>
            <td> {{ $store.state.output[3].fuelCost }} </td>
        </tr>
    </tbody>
</template>
<script>
    export default {
    name: 'LineResultTable'
}

Is there a way to do this trick on HTML? Something like v-if, v-show? I tried to figured it out but nothing until now

CodePudding user response:

You can use Boolean expressions

<td> {{ $store.state?.output[0]?.address || '-' }} </td>

There is no need to use v-if or v-show

CodePudding user response:

You can use this type of single line if-else statement

<td> {{ $store.state.output[0].address!==undefined?'Default value':$store.state.output[0].address }} </td>

Here, the syntax is:

{{ (condition) ? (true block) : (else block) }}
  • Related