Exploring LocalStorage Monitoring in Vue.js 2

How can I stay informed about any changes in Banana.vue?

I have tried using addEventListener, @watch but it doesn't seem to be working...

The index.vue file is importing both Apple.vue and Banana.vue

In Apple.vue:

localStorage.setItem('fruit', 'apple)

In Banana.vue:

@watch(localStorage.getItem('fruit' || '')
    changeFruit() {
    this.fruit = localStorage.getItem('fruit')
}

Answer №1

Implement the getter and setter methods in your code.

data() {
    return {
      get token() {
        return localStorage.getItem('token') || 0;
      },
      set token(value) {
        localStorage.setItem('token', value);
        this.fruit = localStorage.getItem('fruit')

      }
    };
  }

Answer №2

LocalStorage might not be reactive, but you can still retrieve the localStorage value within the component using this approach :

Vue.component('apple', {
  props: ['childmsg'],
  template: '<p>{{ childmsg }}</p>',
  mounted() {
    localStorage.setItem('fruit', 'apple');
  }
});

Vue.component('banana', {
  data: {
    fruit: ''
  },
  props: ['childmsg'],
  template: '<p>{{ childmsg }}</p>',
  mounted() {
    if (localStorage.fruit) {
      this.fruit = localStorage.fruit;
      console.log(this.fruit);
    }
  }
});

var app = new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <apple childmsg="This is Apple"></apple>
  <banana childmsg="This is Banana"></banana>
</div>

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

After employing a combination of forEach and filter queries in JavaScript to sift through dropdown options, no results are being generated

Hey there fellow developers, I'm currently in the process of developing an app and have reached the stage where I am filtering elements using dropdowns. I am querying a JSON object and comparing it with the selected element in the dropdown at that mom ...

When there is data present in tsconfig.json, Visual Studio Code does not display errors inline for TypeScript

After creating an empty .tsconfig file (consisting solely of "{ }"), Visual Studio Code immediately displays errors both inline and in the "problems" section. Interestingly, when I populate the tsconfig.json file with data, these errors disappear. Is there ...

What could be causing the cyclic dependency problem after upgrading to Angular 9?

I am experiencing an issue with a specific file containing the following code: import { Injectable } from '@angular/core'; import { I18n } from '@ngx-translate/i18n-polyfill'; import { isNumber } from 'lodash'; import { Confir ...

What is the best way to determine if several simultaneous tasks have been completed?

Implementing multiple parallel actions in an Angular component has proven to be challenging for me. Following each action (foo), I subscribe to its result. I've been attempting to determine if any actions are currently running or have completed using ...

Setting up Nginx for a static Vue.js website

Recently, I've been trying to set up my nginx vuejs static frontend but have run into a consistent issue where my site keeps returning a 500 error. The configuration file /etc/nginx/nginx.conf that I used was based on the one provided on this site. E ...

Arranging Data in AngularJS based on Selected Filter Criteria

I have a filter function that currently only returns the name values in my table. I would like to add options for both ascending and descending sorting to this filter. Progress So Far: I am able to retrieve values from all inputs, including the name and ...

VueJS: The current date is before today's date when using Date.now

I am currently comparing two dates in order to perform a filtered search. My goal is to only include objects in the filtered results if the date is after today, excluding any objects dated for today. However, when I run my code, it appears that items wit ...

How can I simply show a specific value from an object in Vue?

I've created a Vue application that filters messages and displays them on a page. Currently, when a user selects a message from the list, the entire JSON data associated with that message is shown on the page. However, I want to only display a specifi ...

"Looking to transfer an array of object properties in a Vue.js application? Let's explore

component: To-Do List: <template> <ol> <li v-for="toDo in toDos" :key="toDo.id">{{ toDo.text }}</li> </ol> </template> <script> export default { name: "ToDoList", props: { toDos: Array }, ...

Allowing cross-origin resource sharing (CORS) in .NET Core Web API and Angular 6

Currently, I am facing an issue with my HTTP POST request from Angular 6. The request is successfully hitting the .net core Web API endpoint, but unfortunately, I am not receiving the expected response back in Angular 6. To make matters worse, when checkin ...

Tips for retrieving the present value of a piped/converted BehaviorSubject

How do I retrieve the current value of the observable generated by readValue() below without subscribing to it? var subject = new BehaviorSubject<Object>({}); observe(): Observable<Object> { return subject.pipe(map(mappingfunction)); } Do ...

Basic library using babel, TypeScript, and webpack - Error: (...) is not a recognized function; within Object.<anonymous>

Recently, I encountered a strange issue while trying to bundle a simple function using babel, typescript, and webpack. You can find the example that is not working at this link. To test it, simply download the code, run npm/yarn install, npm/yarn run buil ...

Updating an object within an array of objects in Angular

Imagine having a unique object array named itemArray with two items inside; { "totalItems": 2, "items": [ { "id": 1, "name": "dog" }, { "id": 2, "name": "cat" }, ] } If you receive an updated result for on ...

Challenges with Vuetify grid system in Nuxt: addressing layout inconsistencies, page rendering problems, and component alignment (+ unexpected background color

Attempting to recreate the layout of a login page like the one found here: Mentor Cruise Login Page. I am aiming for a 1/3 vs 2/3 split with a vertically centered login component. Currently, I am using my default.vue layout to control the visibility of th ...

Display the default child of vue-router 4

Need Assistance with Rendering Default Child View in Vue I am currently facing an issue with rendering the default child view for the Category view. I have come across a similar problem discussed on Stack Overflow, but it seems to be related to VUE2 and o ...

Retrieving the current user using Vue/Axios within the Laravel framework

Currently, I am looking for the most efficient way to load the current user into my Vue app in order to access the username and ID from any component or route. At this point, I have attempted the following approach: app.js new Vue({ el: '#app&apos ...

Creating a unique custom pipe in Angular 5

Recently, I started learning Angular and encountered an issue that I'm struggling with. I am trying to develop a custom pipe that can convert decimal codes into base64 images and then display them in views. Even though I have the complete code to add ...

Angular is unable to start the variable_INITIALIZation process

I've created a method called get that returns data of type ProductModel. getProduct(id:number): Observable<ProductModel[]> { const url = `${'api/product/getProductById/'}/${id}`; return this.http.get<ProductModel[]>(u ...

Retrieve the values stored under the "kilos" key for every object in the dataset

Recently, I stumbled upon the following code snippet: data = [ 0: {kilos: 10}, 1: {other:1, kilos: 5}, 2: {other:2, kilos:6} ] After analyzing it, I realized that I need to extract all the values associated with the "kilos" keys and then calculat ...

Ways to incorporate forms.value .dirty into an if statement for an Angular reactive form

I'm a beginner with Angular and I'm working with reactive Angular forms. In my form, I have two password fields and I want to ensure that only one password is updated at a time. If someone tries to edit both Password1 and Password2 input fields s ...