Display a default value if the state's value is not defined | Vue.js 3

In a Vuejs 3 component, the code below is functioning perfectly with no issues. However, I am looking to display something specific when there is no output:

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

If the above code is undefined or does not exist, I would like it to show '-' instead of an error.

<template>
    <tbody class="text-center">
        <tr class="table-default">
            <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 in HTML to achieve this using v-if or v-show? I have been attempting to resolve this without success so far.

Answer №1

Utilize Boolean operations for more concise code

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

Avoid unnecessary v-if or v-show directives

Answer №2

If you ever need to conditionally output content in one line, consider using the single line if-else statement.

<span> {{ $user.isAuthenticated?'Welcome back': 'Please log in' }} </span>

The format of this statement is as follows:

{{ (condition) ? (output if true) : (output if false) }}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sorting arrays in ES5 with the sort() method

In my array, I have multiple objects with a 'time' property that stores date strings. elements = [ {time: "2013-03-01T10:46:11Z"}, {time: "2013-03-03T10:46:11Z"}, {time: "2013-03-02T10:46:11Z"} ] My goal is to ...

Trouble with jQuery script causing initial word count issue in textarea upon page load

I have implemented a word count textarea jQuery script and I am trying to figure out how to update the word count onload to 2 when the text area initially displays "this example". Currently, it shows 0 words. Although I can set focus on it and move the c ...

The filtering function stops working after the initial use

As I develop an app using React and Redux, my goal for the following code snippet is to function as a reducer within the main application. I have imported a filterData function, which works seamlessly the first time any Action type is selected. However, it ...

What is the best way to retrieve the biggest image (based on dimensions) from a website using the URL?

As an example, when I enter: http://www.google.com/ The result would be: http://www.google.com/images/logos/ps_logo2.png This would be accomplished using javascript/jquery. All the websites involved are external. Appreciate your help! ...

Transform the JSON response from MongoDB into a formatted string

var db = mongoose.connection; const FoundWarning = db.collection('warning').find({UserID: Warned.user.id, guildID: message.guild.id}).toArray(function(err, results) { console.log(results); }) I have been attempting to ...

Tips for moving text within a Canvas using a button to trigger the function that displays the text in a Javascript environment

Within my HTML, there is a canvas element with the id="myCanvas". When a button is clicked, it triggers this particular function: function writeCanvas(){ var can = document.getElementById("myCanvas"); var ctx = can.getContext("2d"); va ...

Create a div element that can be expanded on smaller devices

Is it possible to expand a div while hovering on a small or x-small device? I want to achieve something like this: https://i.sstatic.net/doJKa.png Currently, I can only hide the yellow div when the page is displayed on a small device. I am looking for a ...

Guide to resolving a blank webpage issue post running 'npm run build'

I am currently in the process of working on a project that involves Vue and Firebase. Unfortunately, I have encountered an issue where my development server is no longer rendering new routes from my Vue router after building and deploying to production. F ...

Tips for displaying lower quality images while initially downloading higher quality versions

I need to download and display a large image in an img tag. Since the image is not Progressive JPEG, it will render as it downloads. Is there a way to show a low-resolution version of the image while it fetches from the server using only CSS or an HTML p ...

Tips for using a JavaScript function to navigate to a specific division (<div>) on an HTML page

I am facing an issue where I need to redirect within the same HTML page that includes a add-form div. What I want is that when I click on a button, my redirection should be to a specific div containing some code. Currently, I have code that redirects to a ...

Experience the advanced NgPrime p-dropdown template with templating, filtering, and a clear icon that collapses when wrapped within a form element

Check out this link for a demo Whenever I enclose the code below in a </form> element, the drop-down menu collapses. <h5>Advanced with Templating, Filtering and Clear Icon</h5> <p-dropdown [options]="countries" [(ngModel)]=& ...

Local copies of the Javascript game will have objects spawn in the game, but when uploaded the objects

I'm currently developing a simple Javascript game where the objective is to avoid falling objects using GameQuery. The game features frequent enemy spawns and occasional power-ups. I noticed that the power up spawn function is essentially a duplicate ...

Understanding the problem of scope within a JavaScript object literal

Just diving into the world of programming and joining this community for the first time. I'm currently grappling with a scope issue involving object literals in my code. Any assistance would be greatly appreciated! var obj = { value: 3, print:() ...

Why is my Express Router being called twice?

When I call server.js, it in turn calls index.js via a route. The issue I am facing is that the router in index.js is being called twice when the page is accessed, resulting in the message "/ (Console.log inside router.use(async (req, res, next) => { fr ...

Tips for modifying style.display using JavaScript

On my website, the menu is structured like this: <nav id="menu"> <label for="tm" id="toggle-menu">Menu <span class="drop-icon">▾</span></label> <input type="checkbo ...

``Is there a way to retrieve the value of a Vue object with the help of Selenium WebDriver?

My HTML code snippet is as follows: <div data-v-58fe9fbf="" data-v-5de8f7f2="" class="copy-button" id="cta_get_link"> <input data-v-58fe9fbf="" type="text" readonly="readonly" c ...

What is the process for declaring a component within the <script setup> section?

What is the process for registering a component within <script setup>? ...

Discovering the specific element that was clicked from a collection of elements

I'm dealing with a scenario where multiple divs share the same class. There is a dropdown that alters the background color of one of these divs when a certain option is selected (for example, option 2 changes div #2's background color). My dile ...

Choose links in the div and apply "motion effects."

Can anyone help me figure out why the color change for links in a div on mouseover/mouseout isn't working? Here is the HTML code: <div id="Navigation"> <a href="#">Products</a> <a href="#">Pro ...

Importing a JavaScript file into another JavaScript file

var FS = require('fs'); var Path = require('path'); var Jsonfile = require('jsonfile'); var search = function () {}; search.prototype.projectContainerDirPath = null; /* * interface */ search.prototype.setPaths = function ...