Interactive navigation feature developed using VueJS

Attempting to implement a reactive navigation system that changes based on user authentication status. Following a login action in the application, a token is stored in local storage. If this token exists, I aim to display a logout button. Despite trying various approaches such as computed properties, standard methods, and props, the desired reactivity is not achieved.

After logging in, the navigation does not update dynamically. However, upon refreshing the page or resetting the app, the logout button appears as expected.

What could be causing this issue?

Diving into Vue JS has been a challenge for me, with hours spent struggling to understand the concepts. Tasks that were straightforward server-side are taking much longer client-side. Where is the promised reactivity?

Nav.vue

  <template>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
      <a class="navbar-brand" href="#">App</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarColor01">
        <ul class="navbar-nav">
          <li class="nav-item active">
            <a class="nav-link" href="#">
              <router-link to="/">Home</router-link>
              <span class="sr-only">(current)</span>
            </a>
          </li>
          <li class="nav-item">
              <router-link to="/about" class="nav-link">About</router-link>
          </li>
        </ul>
        <ul class="navbar-nav ml-auto">
          <li class="nav-item" v-if="hasAuth()"><a @click="logout()" class="nav-link">Log Out</a></li>
          <template v-else> 
            <li class="nav-item">
              <router-link to="/register" class="nav-link">Register</router-link>
            </li>
            <li class="nav-item">
              <router-link to="/login" class="nav-link">Login</router-link>
            </li>
          </template>
        </ul>
      </div>
    </nav>
  </template>

  <script>
  export default {
    name: 'Nav',
    data: () => {
      return {
        auth: false
      }
    },
    methods: {
      logout: function () {
        localStorage.removeItem('user-token');
        this.$router.push({ path: 'login' });
      },
      hasAuth: function () {
        this.auth = (localStorage.getItem('user-token')) ? true : false;
        return this.auth
      }
    },
  };
  </script>

App.vue

<template>
  <div id="app">
    <Nav></Nav>
    <router-view/>
  </div>
</template>

<script>
import Nav from '@/components/Nav.vue';

export default {
  components: {
    Nav,
  },
}
</script>

Answer №1

Even though Vue.js is reactive, localStorage does not possess this same quality. It is impossible for Vue to detect whether the localStorage has been modified or not because there is no local change event available with local storage.

To address this issue, it is recommended to utilize Vuex in conjunction with Local Storage for persistent data storage. When you save the token to local storage, also store a duplicate copy within the Vuex state at that point.

For instance, another component such as Nav should access data from the Vuex store, which is reactive. Upon refreshing the page, initialize the Vuex store using the information stored in the localStorage.

By implementing this method, you can establish a seamless and fully reactive system.

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

Attempting to delete a request using FormData resulted in a 500 error response

Currently, I am working on deleting an attachment by sending a request with form data containing a URL through an API path along with an ID. deleteAttachment(id, url) { const formData = new FormData(); formData.append('url', url); ...

Effortlessly browse through directory with the seamless integration of AngularJS or

Hey there! I'm working on a really cool feature - creating a list with editable inputs. However, I've encountered a bit of an issue. Is there any way to navigate through this list using arrow keys and focus on the desired input? .content ul { ...

Convert the data received from jQuery $.parseJSON into HTML code

I am using $.parseJSON to retrieve data from a specific URL. The link I receive contains {"status":"ok", "message":'<form><input type="text" name="" value=""> </form>'} Now, I want to add the "message" part to my content. $. ...

Asynchronous NestJs HTTP service request

Is there a way to implement Async/Await on the HttpService in NestJs? The code snippet below does not seem to be functioning as expected: async create(data) { return await this.httpService.post(url, data); } ...

Exploring a collection of objects housed in a json document

Currently, I'm looking to retrieve a collection of objects using JavaScript from a JSON file that resides on my website. While I could easily embed the array of objects directly into my JavaScript code, I am interested in understanding how to work wit ...

Struggling with retrieving the $id variable from the view in both the controller and the database through Ajax

While checking my view, I noticed that the variable $id is visible. However, when I send it through Ajax, it ends up as NULL in the database. The way I'm sending the variable $id from the view using Ajax is like this: $.ajax({ url:'{ ...

Obtain attributes from an array of objects organized by the individual objects

Hello there! I am currently working with an array called artists[] which consists of Proxy objects. Each Proxy object is also an array of objects, with each inner object containing a property called "artistName". Interestingly, the third Proxy ha ...

I'm curious, in TypeScript, how can I access a class variable from within a method

I've hit a roadblock and can't seem to figure it out. Despite scouring the forum and tirelessly searching on Google for hours, I'm unable to solve this issue! This is my first attempt at creating an app with Angular, and it's safe to sa ...

How to deliver various static files in NestJS using different paths and prefixes?

I've set up static file serving for developer documentation using the following code: app.useStaticAssets(docsLocation, { prefix: "/docs/" }) Now I have another directory with more static content that I want to serve. Is it possible to serve from ...

The extent of locally declared variables within a Vue component

Within this code snippet: <template> <div> <p v-for="prop in receivedPropsLocal" :key="prop.id" > {{prop}} </p> </div> </template> <script> export default ...

How can I iterate through all elements of a JavaScript object using slice, excluding the first two elements?

Is it possible to loop through all objects in an object, excluding the first two, without creating a new object? I have tried using slice but it only works on arrays. This is what my object looks like: { First: { }, Second: { }, Third: { } } ...

Accessing data from a live database in a randomized sequence

When retrieving items from a database, there is often a common code pattern that looks like this: const [dataRcdArray, setDataRcdArray] = useState<never[]>([]); ..... snapshot.forEach((child:IteratedDataSnapshot) => { setDataRcdArray(arr ...

Develop a unique splitter code that utilizes pure javascript and css, allowing users to drag and drop with precision

I am facing an issue with setting the cursor above my drop panel, as it results in a flicker effect. How can I set the cursor for my example to work properly? I have tried multiple different approaches to make this work. Although I am using the provided ...

Having trouble formatting the date value using the XLSX Library in Javascript?

I'm having trouble separating the headers of an Excel sheet. The code I have implemented is only working for text format. Could someone please assist me? const xlsx = require('xlsx'); const workbook = xlsx.readFile('./SMALL.xlsx') ...

Error: OpenAI's transcription API has encountered a bad request issue

const FormData = require('form-data'); const data = new FormData(); console.log('buffer: ', buffer); console.log('typeof buffer: ', typeof buffer); const filename = new Date().getTime().toString() + '.w ...

Backbone and Laravel - Choose a squad and automatically create users for the selected team

I've recently started exploring backbone.js and have gone through Jeffery Way's tutorial on using Laravel and Backbone. As of now, I have a list of teams being displayed along with their ids fetched from the database. I have also set up an event ...

The values entered in the React form inputs are not displaying accurately

I'm currently working on a project that involves creating a form for tours. Everything seems to be working well, except for the issue of input values getting mixed up. For example: Actual output: { tourName: 'pune darshan', location: &apos ...

v-for loop doesn't iterate over imported array

I am facing an issue with importing data from a file named clients.js into another file called clients.vue. My goal is to display the imported data in a table within the clients.vue file, but I am unable to access it after importing. Interestingly, if I c ...

exchanging the positions of two animated flipdivs

Hey there! I'm facing a little challenge with my two divs (let's call them div1 and div2). One of them has a flip animation on hover, while the other flips on toggle click. My goal is to swap these two divs by dragging and dropping them. I' ...

Creating concise one-liner If statements with Handlebars: a simple guide

I am seeking clarification on the correct syntax for this code snippet: <li class="nav-item {{# if undefined !== user}} hidden {{/if}}"> My goal is to add the class name hidden only if the user variable exists. When I try implementing this, it res ...