Vue.js problem with conditional rendering using v-if

I'm struggling to grasp the concept behind how v-if functions. My goal is to dynamically hide buttons in the navigation bar based on the user's authentication status and current page. Specifically, I want the "My Account" button to be displayed when the user is logged in, and show the sign-up/log-in buttons when they are not. Additionally, if the user is on the "Activate My Account" page, I do not want any buttons to appear in the nav bar. I have attempted to create a method that returns the path of the activation page. However, uncommenting the following code snippet causes the sign-up/login buttons to disappear as intended, but also hides the "My Account" button.

        <template v-else-if="isNotInConfig">
          </template> 

Here is my current code:

            <div class="navbar-end">
                <div class="navbar-item">
                    <div class="buttons">
                        <template v-if="$store.state.user.isAuthenticated">
                            <router-link to="/dashboard/my-account" class="button is-primary is-outlined">My account</router-link>
                        </template>
                        <!-- <template v-else-if="isNotInConfig">
                        </template> --> 
                        <template v-else>
                            <router-link to="/sign-up" class="button is-primary" ><strong>Sign up</strong></router-link>
                            <router-link to="/log-in" class="button is-light">Log in</router-link>
                        </template>

                    </div>
                </div>
            </div>

<script>
export default {
    data() {
        return {
        }
    },
  methods: {
    isNotInConfig() {
      return this.$router.history.current["path"] == "/activate/:uid/:token";
    }
  },
};
</script>

Answer №1

If you want to customize your buttons based on certain conditions, you can try the following approach:

  <template v-if="isNotInConfig()">
    <template v-if="$store.state.user.isAuthenticated">
      <router-link to="/dashboard/my-account" class="button is-primary is-outlined">My account</router-link>
    </template>
    <template v-else>
      <router-link to="/sign-up" class="button is-primary" ><strong>Sign up</strong></router-link>
      <router-link to="/log-in" class="button is-light">Log in</router-link>
    </template>
  </template>

Additionally, include the method below to toggle the display of the buttons:

isNotInConfig() {
  return !this.$route['path'].includes("/activate");
}

By enclosing the button logic within

<template v-if="isNotInConfig()">
, you ensure that they are only visible when not on the "activate my account" page.

Remember to use strict equality (===) for comparisons to avoid type coercion.

For more information on this topic, refer to this resource.

Answer №2

The concept of using v-if, v-else-if, and v-else in Vue.js is similar to conditional statements in other programming languages. Initially, it checks the condition in the if statement. If the condition is not true, it moves on to check the else if statement, and so forth.

In your scenario, when isAuthenticated is true, it will always display "my account". However, if isAuthenticated is false, it will then evaluate the isNotInConfig condition before proceeding to v-else.

It is important to remember that the placement and nesting of HTML elements in your template are crucial! Any comment between v-if and v-else can disrupt the flow and prevent the evaluation of v-else, resulting in the content always being rendered.

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

Interacting with an iframe element using Selenium in Python

I have a webpage with an iframe embedded, and I'm using Selenium for test automation: <iframe class="wysihtml5-sandbox" security="restricted" allowtransparency="true" frameborder="0" width="0" height="0" marginwidth="0" marginheight="0" style="dis ...

Issues with lazy loading in swiper.js when trying to display multiple images per slide

I recently tried using swiper.js and had success with the lazy loading demo. However, I encountered an issue where only one image per slide was showing up, despite wanting to display 4 images per slide. <div class="swiper-container"> <div cla ...

Evaluating Vue with AVA - The key is in the whitespace

Currently, I am engrossed in a Laracast Episode about Vue Testing with AVA. Everything has been going smoothly so far, but now I have encountered an intriguing bug. This is my notification.js: import test from 'ava'; import Notification from &ap ...

The React rendering process failed when attempting to utilize a stateless component

Struggling to integrate a stateless component with fetch in my project. The fetch API is successfully retrieving data, but for some reason, the stateless component remains blank. import React, { PropTypes } from 'react'; import { Card, CardTitle ...

Attempting to transpile JavaScript or TypeScript files for compatibility within a Node environment

Our node environment requires that our JavaScript files undergo Babel processing. Figuring out how to handle this has been manageable. The challenge lies in the fact that we have a mix of file types including .js, .jsx, .ts, and .tsx, which is not subject ...

The jQuery dropdown menu smoothly expands to reveal all hidden submenu options

I'm currently encountering an issue with jQuery. I am trying to create a responsive drop-down menu with sub-menus. The behavior I want is that if the window width is less than 700px, the submenus will trigger onClick. And if the window is wider than 7 ...

Issue with SetTimeout not functioning properly on initial use within socket.io

Currently, I am trying to come up with a method to retrieve an IP address from a node server that is hosted on a dynamic IP. The issue I am facing is that the setTimeout function does not seem to work properly on the server side during the initial launch. ...

Preventing direct URL access with Angular redirects after refreshing the page

My website allows users to manage a list of users, with editing capabilities that redirect them to the /edit-user page where form information is preloaded. However, when users refresh the page with F5, the form reloads without the preloaded information. I ...

Error: The variable 'error' could not be located

Below is the code that I am using: $(document).ready(function(){ var callPage = function(){ $.post('/pageToCall.php'); }; setInterval('callPage()', 60000); }); However, I encountered an error stating ReferenceErro ...

`Can you provide instructions on modifying CSS using JavaScript once the window size reaches a specified threshold?`

Is there a way to use JavaScript to automatically adjust the font size when the screen reaches 1050px? ...

How can we deliver pure JS, HTML, and CSS content without relying on static HTML pages?

Looking to create a fast app prototype without using React or Vue? I'd like to avoid simply making an html and js file imported within it. Can npm packages, SCSS be used while programming vanilla Javascript minus a framework? ...

The specified type does not meet the constraint as it lacks the required index signature

I'm currently working on refactoring a TypeScript project that utilizes React Hooks. While I have some knowledge of TypeScript, I am still more of a beginner than an expert. My main goal is to create reusable code for this project through the use of ...

Updating the "title" attribute dynamically using jQuery in real time

I have a span that displays data in a tooltip every second, fetched from the server: <span class="info tooltip" title="{dynamic content}"></span> To show the tooltip, I'm using the tooltipsy plugin: $('.tooltip').tooltipsy({ ...

Which event occurs first for a4j:jsFunction, reRender or oncomplete?

After running a jsFunction, I want the javascript to execute once the re-rendering is completed. I assume that the "oncomplete" javascript function is triggered after the re-rendering process, but I'm not entirely certain. Any insights on this? Appre ...

How do I execute 2 functions when the button is clicked?

<button id="take-photo"> Take Image</button> <button type="submit" value="Submit" >Submit </button> How can I trigger two tasks with a single button click? 1. Executing a function based on ID Next 2. Submitting the form with ...

Node.js client-sessions malfunction when not utilized as a primary callback

When utilizing express.Router, I'm attempting to create a middleware for a particular router in my application that will establish and handle a session. However, this approach fails if the client-sessions session is not invoked directly by Router().us ...

retrieving request headers using XMLHttpRequest

Is there a way for me to access my requestHeaders within the onload function? Any guidance on how to achieve this would be greatly appreciated. Many thanks! ...

Introduction to the fundamentals of Vue.js

Recently, I've been diving into learning Vue.js on my Mac. I installed it using Terminal, created a new folder, opened it in Sublime Text, and wrote the following code snippet. However, when I tried to view it in the browser, nothing seems to work. An ...

What is the reason for node executing both of these handlers on the server?

My node app is set up with two handlers, one for requests to the root URL and another for the slug. However, when I visit the root or slug URLs, the app crashes and I receive this error: url is pointing to root url has a slug throw err; // Rethrow non-MySQ ...

The custom error page in NextJS is failing to display

In my custom pages/404.ts file, I have coded the following: export default function NotFound() { return <h1>404 - Page Not Found</h1> } Additionally, there is another page that displays a 404 error when the organization is null: import Error ...