Utilize Vue Component by assigning a computed property to the data source

Trying to assign a computed property value to a component's data in order to fetch and manipulate localStorage data.

After mounting the component, I want to monitor changes in the localStorage. If my key is updated, I need to retrieve the new value, process it using the computed property, and display it on the view.

Encountering the following error:

ReferenceError: ids is not defined
    at a.render (vue.js:4)
    at a.e._render (vue:6)
    at a.r (vue:6)
    at un.get (vue:6)
    at new un (vue:6)
    at vue:6
    at a.bn.$mount (vue:6)
    at a.bn.$mount (vue:6)
    at init (vue:6)
    at vue:6

This is the code for my component:

Vue.component('favourites-button', {
    render() {
        return this.$scopedSlots.default({
            count: this.ids.length
        });
    },
    data: function() {
        return {
            ids: this.getFavourites()
        }
    },
    mounted() {
        const self = this;
        Event.listen('favourites-updated', function (event) {
            console.log('updated external');
        });
        window.addEventListener('storage', function (e) {
            if (e.key === 'favourites') {
                console.log('updated');
                self.ids = self.getFavourites();
            }
        });
    },
    methods: {
        getFavourites: function() {
            let favourites = localStorage.getItem('favourites');
            return favourites.split(',').filter(id => !!id);
        }
    }
});

Edit:

Made adjustments to my code but still facing the same error when the storage change event occurs.

Edit 2:

Discovered that my template was expecting toggle within the scope, despite removing it from my $scopedSlots.

Answer №1

If you want a more efficient way to handle this, consider using computed properties. You'll just need to create a getter and setter for it.

computed: {
  fullName: {
    // getter
    get: function () {
      return localStorage.getItem('favourites')
    },
    // setter
    set: function (newValue) {
      localStorage.setItem('favourites', newValue)
    }
  }
}

In my opinion, this approach is much neater compared to the traditional method of using mounted callback, setting data, and then watching for changes.

Answer №2

Utilizing computed properties is effective when operating on data/props, as they cannot be used directly in the data itself.

To work around this limitation, simply assign the initial value of the data key to match what is stored in local storage:

data: function () {
    return {
        ids: function() {
            let favorites = localStorage.getItem('favorites');
            return favorites.split(',').filter(id => !!id);
        }
    };
}

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

Is it possible to use function declaration and function expression interchangeably?

As I dive into learning about functions in Javascript, one thing that's causing confusion for me is the difference between function declaration and function expression. For example, if we take a look at this code snippet: function callFunction(fn) { ...

What is the best way to insert CSS code into a custom Vue directive file?

I need a solution that applies a gradient background to the parent div in case an image fails to load. I've attempted to create a directive for this purpose: export default { bind(el: any, binding: any) { try { ..... ...

What is the timing for when the SignalR connection is terminated from the browser?

Currently, I am developing a chat application using SignalR 2.0, like many others in the same field. In my Win8.1 application, when the user closes the application, the hub receives the OnDisconnected event and removes the user from the list on the hub. A ...

Clear previous loop data in PHP

I have a "show recent" pictures div on my website that I want to refresh every 20 seconds to display a new picture. However, the issue is that my current ajax call refreshes instantly instead of after 20 seconds and it fails to delete the previous data, re ...

Using values from a select menu in a math calculation without including a decimal point

I am working with a dropdown menu that contains various values... <select id="number1a" onChange="Addition()"> <option value="0" selected>-</option> <option value="10">10</option> <option value="7.5">7.5</optio ...

Unraveling the Mystery of Passing Props in React.js

Currently taking an online course to learn React, I encountered a unique scenario where one property is attached to another property in this manner: this.props.property01(this.props.property02) The tutor briefly touched on this code line, leaving me quit ...

Issues arise when using bootstrap-multiselect onDropdownShow

I am currently utilizing the bootstrap-multiselect plugin created by davidstutz in conjunction with twitter bootstrap 3.3.0. My goal is to have a radio button selected when I click on the dropdown, however, this functionality does not seem to be working a ...

React-router can manage non-matching paths by utilizing a basic JavaScript router configuration

Is there a way to manage non-matching paths using plain JavaScript in React router configuration? const rootRoute = { component: 'div', childRoutes: [ { path: '/', component: App, childRoutes: [ requir ...

What is the best way to eliminate concealed divs from the view source of a webpage?

On my HTML page, I have some hidden DIVs that can still be viewed in the page source. I want to ensure that these DIVs are not visible to users when they inspect the page source. Is there a way to achieve this using Javascript or another solution? ...

Encountering the error of receiving "$ undefined," despite making a reference to the library

I have included the JQuery library in the following way: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script> Despite trying to download the library and include it locally in my project, I ...

Creating a responsive layout that sets the window height to 100% and automatically adjusts sibling divs when the content within parent divs exceeds the defined height

<section> <div class="section-wrap"> <h1>page1</h1> </div> </section> <section> <div class="section-wrap"> <h1>page2</h1> </div> </section> My attempt at impleme ...

Experiencing Elevated CPU Usage and Memory Capacity Exceeded Problem during npm run build in Laravel with Vue.js utilizing Vite

Currently, I am encountering a severe challenge while working on a Laravel project that incorporates Vue.js with Vite as the build tool. The issue arises when I run npm run build, causing the CPU usage to skyrocket to 100%. This ultimately leads to a deple ...

Looking for a way to add a permanent footer to the bottom of your webpage without affecting the tab order for accessibility?

I have a paginated form with a fixed navigation footer at the bottom that needs to stay in place even when scrolling. This footer should also be at the bottom of the page for mobile devices and tablets. To achieve this, I used position: fixed on the foote ...

Delivering static assets through a POST request with express.js

I'm having an issue serving static content for a Facebook app using express.js app.configure(function (){ app.use('/', express.static(__dirname + '/public')); }); Everything is working fine with a GET request, but when I try ...

Can Angular 4 experience race conditions?

Here is a snippet of my Angular 4 Service code: @Injectable() export class MyService { private myArray: string[] = []; constructor() { } private calculate(result): void { myArray.length = 0; // Perform calculations and add results to myAr ...

What is the solution to the problem "How can you resolve the issue where 'Cannot set property 'ref' of undefined' occurs"?

My goal is quite simple - I just want to retrieve data from Cloud Firestore. Below is the code snippet I am using: import React from 'react'; import firebase from "react-native-firebase"; export default class newsFeed extends React.Component { ...

"How can I open a DOCX file in a new window using JavaScript and then close the window

When attempting to open a doc/docx file in Word from an HTML link, my goal is to prevent the opening of a new browser window. First attempt: mywin=window.open("filename.docx","viewer"); The first attempt works fine, but it results in opening a new "view ...

What steps should be taken to effectively integrate Amplify Authenticator, Vue2, and Vite?

Embarked on a fresh Vue2 project with Vite as the build tool. My aim is to enforce user login through Cognito using Amplify. However, when I execute npm run dev, I encounter the following issue: VITE v3.1.3 ready in 405 ms ➜ Local: http://127.0.0 ...

Is there a way to make JavaScript function properly with PHP-generated content?

I have a PHP file that loads a variety of forms depending on an identifier passed through a GET request. Everything is functioning properly, except for my JavaScript/jQuery code. Is there a way I can refresh the JavaScript to make it work with the form? ...

How to utilize local functions within a ko.computed expression

Why isn't this line of code working? I'm using durandal/knockout and my structure is like this define(function () { var vm = function() { compute: ko.computed(function() { return _compute(1); // encountering errors }); ...