Tips for efficiently handling navigation re-rendering on a Single Page Application using Vue.js

I am currently in the process of developing a Single Page Application using Vue.js. The structure involves having a template in App.vue which includes a navigation bar followed by a router-view component. When a user attempts to log in, a modal window appears and sends a login request to the API.

The main challenge I am facing is figuring out how to dynamically update the navigation bar after a successful login. Specifically, I want to hide the options for logging in and registering once a user has logged in. While I understand that I could use a conditional v-if="user" approach, I am unsure about how to pass this 'user' variable back from the modal component after a login attempt.

App.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/head_img.png">
      <nav>
        <ul>
          <li><router-link to="/games">All games</router-link></li>
          <li><router-link to="/">Home</router-link></li>
          <li><modal-login>Login</modal-login></li>
          <li><modal-register>Register</modal-register></li>
          <li v-if="user">Logout</li>
        </ul>
      </nav>
      <router-view></router-view>
  </div>
</template>

<script>
import ModalLogin from './components/ModalLogin.vue'
import ModalRegister from './components/ModalRegister.vue'

export default {
  name: 'app',
  components: {
    ModalLogin,
    ModalRegister
  }
}
</script>

Modal Example

<template>
    <div>
        <a href="/#register" @click.prevent="show">Register</a>
        <modal name="modal-register" @opened="opened">
            <form @submit.prevent="doRegister">
                <div class="form-group">
                    <label for="email" class="block">Email</label>
                    <input v-model="email" type="email" id="email" name="email" class="border" ref="email">
                </div>
                <div class="form-group">
                    <label for="password" class="block">Password</label>
                    <input v-model="password" type="password" id="password" name="password" class="border">
                </div>
                <div class="form-group">
                    <button type="submit">Register</button>
                </div>
            </form>
            <div class="form-group">
                <p>Already have an account? <a href="#" @click.prevent="showLogin">Login</a></p>
            </div>
        </modal>
    </div>
</template>

After sending the request, I have included a .then statement to verify the status of the request (201).

I would greatly appreciate any guidance or suggestions on how to effectively handle this particular task.

Answer №1

To ensure user authentication status is set globally, utilize Vuex.

Below is an example code snippet to illustrate:

const state = {
  isAuth: false
}

const mutations ={
  setAuth:(state,value)=>state.isAuth = value
}

const actions = {
  loginRequest:function({commit}){
    // perform login request
    commit('setAuth',true); // execute this after receiving the login response
  }
}

In your component, include a computed function as follows:

computed:{
  isAuth:function(){
    return this.$store.state.isAuth;
  }
}

You can now use isAuth to manage conditions for hiding specific sections.

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

Explaining Vue.js actions and mutations in detail

Can someone help clarify the relationship between these functions for me? I'm currently learning about Vue.js and came across an action that commits a mutation. The Action: updateUser({commit}, user) { commit('setUser', {userId: user[&ap ...

api for enhancing images in Laravel app through preview, enlarge, and zoom functionalities

As I work on my website, I aim to display images in a compact space, such as within a 300x300 <div>. What I envision is the ability for users to preview or enlarge these images upon clicking, allowing for a closer and more detailed view. For exampl ...

Exploring the JSON data in Javascript using Ajax

Completely new to Javascript, I am just trying to grasp the basics of the language. Currently, I have a JSON request set up with the following code: function request(){ $.ajax({ dataType: "jsonp", type: 'GET', url: "getWebsite", ...

Tips for effectively utilizing the useDraggable and useSortable hooks within the dnd-kit library

I'm currently working on developing a basic calculator using React and dnd-kit. The idea is to have draggable elements in the calculator that can be sorted within a droppable area with smooth animation effects. However, I've encountered an issue ...

Utilizing jQuery to extract the value of a selected list item on click

I have been working on creating a list of items from JSON data and am facing an issue with retrieving the 'data-value' attribute of the clicked item. Here is my current code: const target = $('#list'); target.empty(); for (let i = 0 ...

Can the function be executed without the need for ng-app?

After researching my AngularJS application, I discovered that having 2 ng-app tags in the html file means only the first one will be executed. In my code snippet below <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"> ...

Creating an array with conditional elements in React involves utilizing the map method along with a conditional

My array, named tableFilterFields, looks something like this: const tableFilterFields = [ { label: "Start Date", name: "StartDate", type: FilterControls.DatePicker, defaultValue: new Date(new Date().setDate( ...

Creating fixed-size arrays within a Mongoose schema is a commonly sought after feature that allows

For a specific scenario where I have example input: [[1,2],[3,2],[1,3],...,[4,5]] I am wondering about the correct way to define a model schema in mongoose. Here is my initial Schema: const SubproductSchema = new Schema({ ... positions: [{ type: ...

Failed to send JSON data to WebMethod

I am encountering difficulties while attempting to send JSON to a WebMethod. I have provided the method I am using below. If there is a more efficient approach, please advise me. My goal is to store the JSON object in a database. JavaScript function TEST ...

How can components be utilized with v-edit-dialog?

Hey there, I've been exploring the v-edit-dialog component offered by Vuetify and had a query about its implementation. Currently, I'm structuring my v-data-table in a way where I'm importing a component with props into a template slot. The ...

Overriding the Ajax URL

During an AJAX request in a Rails app triggered by onchange event, I am encountering an issue with the URL being called. The function for the request is a simple PUT operation: function quantityChange(id, val) { $.ajax({ url: 'cart_items/ ...

performing asynchronous iteration with HTTP PUT requests

I'm attempting to send multiple HTTP PUT requests to my server, but I am only able to successfully send one JSON object to the database. What could be missing in my code? var data1 = JSON.stringify(require('./abc.json')), data2 = JSON ...

Utilizing jQuery to Adjust Tab Transparency

I'm trying to add some opacity to my jQuery tabs, but so far I've only been successful with accordions. Any tips or tricks for achieving this effect with tabs? Styling with CSS .ui-tabs{ background-image: none; background: rgba(204, 204 ...

What is the best method for animating a display table to none or reducing its height to

My goal is to animate a header whenever the class collapseTest is applied. After some trial and error, I have come up with the following solution: http://jsfiddle.net/robertrozas/atuyLtL0/1/. A big shoutout to @Hackerman for helping me get it to work. The ...

Reveal a segment of a picture

Is there a way to display only a section of an image using either jQuery or another JavaScript method? For example: image: [ ] [ -------- ] [ - - ] [ - part - ] [ - - ] [ -------- ] [ ...

Customize the appearance of every other column in an asp gridview

Looking for help with formatting rows and columns in an ASP GridView. The rows are automatically colored alternating, and I want to make the content in every first column bold and every second column normal. I have heard about using CSS nth-child() to achi ...

The image fails to display when using THREE.js and Panolens.js

Trying to create a 360-degree environment with informational buttons using THREE.js and Panolens.JS However, I'm unable to resolve why the image is not appearing. Continuously encountering the error: Uncaught ReferenceError: process is not defined. ...

Check that EACH radio button has been either selected or left unselected when the button is clicked

I'm still learning Javascript and currently working on a function triggered by a button click. My goal is to display an alert if NONE of the radio buttons have been selected, regardless of whether they are "Yes" or "No." If ALL radio buttons have been ...

Retrieving a single object in NEXT.JS and MongoDB can be achieved by returning just a single object

Is there a way to retrieve a single object instead of an array from the API? I am specifically looking for just a single "Event" while using MongoDB and Next.js. Currently, I always receive: [{}] But I would like to receive: {} const fetchWithId = (url ...

Obtain the selected dropdown value and transfer it to the controller seamlessly without the need to reload the page

Currently, I am facing an issue with two dropdown lists in a bootstrap modal - CATEGORY and SUBCATEGORY. The values in the SUBCATEGORY list depend on the selection made in the CATEGORY list. My goal is to retrieve the selected value ID and pass it to my co ...