The computed value in Vue.js does not execute during initialization

Every time my vm is created, the computed values get function fails to run, leaving the value unassigned.

Oddly enough, it does run when I attempt to access the value, just not during the initial app startup.

Essentially, the goal is to calculate the skin value and dynamically update the stylesheet link to load the correct skin on startup or change.

The functionality is there, but the issue lies in the lack of execution during startup. Should I resort to a workaround like fetching the value in the mounted function of the vm? Or am I overlooking something...

    computed: {
        skin: {
            get: function () {
                var mySkin = "my/skin/string";
                if (window.localStorage.getItem("skin") === null) {
                    window.localStorage.setItem("skin", mySkin);
                    jquery("link[id='skin']").attr("href", "css/skins/" + mySkin + ".css");
                } else {
                    mySkin = window.localStorage.getItem("skin");
                    window.localStorage.setItem("skin", mySkin);
                    jquery("link[id='skin']").attr("href", "css/skins/" + mySkin + ".css");
                }
                var hey = this.skin;
                return mySkin;
            },
            set: function (val) {
                window.localStorage.setItem("skin", val);
                jquery("link[id='skin']").attr("href", "css/skins/" + val + ".css");
            }
        }
    }

Answer №1

A computed property refers to a property that is dependent on other data properties.

In this scenario, it might be more beneficial in my opinion to create a `data` property called `skin`, along with a method like `setSkin()` that sets the initial value of the `skin` data property. Additionally, you can include another method called `saveSkin()` to store the property in localStorage.

Afterwards, you can execute the `setSkin()` method within the `mounted()` lifecycle hook.

Template:

new Vue({
  el: '#app',
  data: {
    skin: ''
  },
  methods: {
    setSkin: function() {
      this.skin = ...;
    },
    saveSkin: function() { // use this function to save the skin data in localStorage
      window.localStorage.setItem("skin", this.skin);
      ....
   }
},
 mounted() {
   this.setSkin(); // retrieve skin data from localStorage, etc.
 }
});

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

Guide to sending both JSON data and form data in a single request using Laravel 9

I am working on a form where I need to input multiple images that will be converted into JSON format. The HTML for my form: create.blade.php <form method="post" action="{{ route('m_announcement.store') }}" enctype="mu ...

Failure to execute the success function

My current issue involves making an AJAX call to retrieve a record from the database. Despite console logs showing that the record is successfully returned, the success function fails to execute. function ajaxForParent() { var search = document.getEle ...

Are you experiencing issues with modal contents extending beyond the modal on smaller screens?

I recently installed a modal plugin called blockUI for my image uploading needs. Although I have styled and positioned everything accordingly, I am facing an issue: Whenever I resize the browser screen, switch to my iPhone, or use another screen, some con ...

Using Selenium to trigger a click event on an ng-click directive in AngularJS is not functioning properly

I am currently trying to confirm that a specific external function is being called when an ng-click event occurs. The code for the input declaration is shown below. While everything seems to be functioning properly in browsers, I am encountering issues dur ...

Ways to verify if a user is authenticated without relying on request.session

I am currently developing a web application using Express, Docker, and following a Three-layered architecture. In my app, I store user login information in a session and have blogposts as a key resource. To retrieve the blogpostId from the database in the ...

When attempting to make an AJAX call using the console, an error was encountered stating that the function $.ajax is not available

Currently experimenting with an ajax call from my console to a local server, but encountering an error: VM4460:1 Uncaught TypeError: $.ajax is not a function(…) Here's the code snippet causing the issue: url = 'http://localhost:8080/testform ...

Execute location.replace when the "control" key is pressed

document.addEventListener('keydown', (event) => { var name = event.key; var code = event.code; if (name === 'Control') { location.replace(classroom.google.com) } if (event.ctrlKey) { alert(`Combinatio ...

Implementing a dynamic function with jQuery Tokenize's change event

I'm currently facing an issue with triggering the on change event on the select box from jQuery Tokenize. Below is the code snippet I am working with: <select id="tokenize" multiple="multiple" class="tokenize-sample"> <option value="1"&g ...

Issue with Jquery 1.10.2 not functioning properly on IE10 with JSON data

I am currently experiencing difficulties with parsing JSON data. The following function is causing errors: parseJSON: function( data ) { //Try to parse using the native JSON parser first if (window.JSON && window.JSON.parse) { retu ...

Troubleshooting: Angular 6 Renderer2 Issue with Generating Dynamic DOM Elements for SELECT-Option

Currently, I am attempting to dynamically create a select option using Renderer2. Unfortunately, I am facing difficulties in creating the <Select></Select> element, but I can confirm that the <options> are being successfully created. Due ...

Ways to access the req.user object within services

After implementing an authentication middleware in NestJs as shown below: @Injectable() export class AuthenticationMiddleware implements NestMiddleware { constructor() {} async use(req: any, res: any, next: () => void) { const a ...

Is it possible to track keystrokes without the use of text input fields?

For various unimportant reasons, I need to use JavaScript to create links instead of using the anchor tag. I want the behavior to mimic the anchor tag, allowing users to open a link in a new tab when holding down the Ctrl key or in a new window when holdin ...

jquery dialog box displaying a webpage

I am looking to implement a feature where, upon clicking the edit link in the last column of my dataTable, a separate page for editing should open within a jQuery dialog box. The goal is to seamlessly submit data while providing a user-friendly experienc ...

Utilizing use-immer and promises to effectively handle an API route mapping system

In the process of tackling the issue of double hook calls in Next.js dev mode, I've encountered a challenge with server API calls that cannot handle duplicates. To address this, I opted for fix #4 outlined in the following article, where I decided to ...

What is the optimal approach for moving the dashboard to a separate subdomain in a static Next.js-generated landing page?

Our current setup includes several static pages generated by Next.js using the command next build && next export These pages are hosted on AWS S3. I am wondering if we should create a new app for building a dashboard with Firebase authentication ...

Using Typescript to create an asynchronous function without explicitly declaring a Promise

When you examine TypeScript's async function, you may notice the redundancy with "async" and "Promise<type>". public async test(): Promise<string> { return "Test"; } Is there a way to configure TypeScript to handle async types ...

What is causing the error when using Interfaces and Observable together?

I created a ToDoApp and integrated Firebase into my project, but I am encountering an error. ERROR in src/app/todo-component/todo-component.component.ts(25,7): error TS2740: Type 'DocumentChangeAction<{}>[]' is missing the following proper ...

Executing JavaScript code within a class object using ASP-VB

I'm looking to create a function that will show a Javascript-based notification. I already have the code for the notification, but I'm trying to encapsulate it in a class library as a function. However, I am unsure about what to return from the f ...

The meaning gets blurred when using 'this' in a prototype method

Alright, so I am working on a node application that utilizes express. In this particular application, there's an express route set up like this: var MyObject = require('./myObject') , myObject = new MyObject(); app.post('/api/w ...

Leveraging JavaScript's Document.write() function to generate an HTML hyperlink

I am struggling with a URL stored in a variable (var URL). My initial attempt was this: document.write("<a href='"+url+"'>LINK</a>"); Unfortunately, it is not working as expected. Any suggestions on how to fix this? This is the ex ...