Can you explain the process of retrieving a value from a computed property in vuejs after it has been altered?

In my Vuejs app, I am working on a computed property to return a modified variable value based on a cookie timer.

The logic is straightforward - if the cookie doesn't exist, set the original value and also store it in another variable as a cached value to display. When the cookie is active and not expired, show the cached value from before.

Below is the code snippet:

export default {
  name: 'app',
  components: {
    mainContr,
    glasses,
    watches
  },
  data() {
    return {
      glassKeys: ['blue', 'white', 'brown', 'yellow', 'black', 'small', 'big', 'medium'],
      watchKeys: ['mechanical', 'moonphase', 'bluehands'],
      glassItem: ''
    }
  },
  computed: {
    glasses() {
      var cachedItem,
          initialValue

      if (!this.$cookie.get('stringSuffixs')) {
        initialValue = this.glassKeys[Math.floor(Math.random()*this.glassKeys.length)]
        cachedItem = initialValue
        this.$cookie.set('stringSuffixs', 'Thirty seconds later', { expires: '2m' })
        return initialValue
      } else {
        return cachedItem
      }

    }
  }
}

I suspect that the issue lies within variable scope and hoisting in relation to the immediate parent function, which in this case, is the computed property.

Answer №1

The cachedItem variable is local and gets recreated every time the computed property is evaluated. To make it more persistent, consider declaring it as a data item and using this.cachedItem.

Have you thought about using a method instead of a computed property? Side effects like setting cookies or dealing with random values are better suited for methods rather than computeds.

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

Tips for building forms with VUE?

Today is my first attempt at learning VUE, and I've decided to follow a tutorial on YouTube from freeCodeCamp.org. The tutorial covers the concept of components in VUE, specifically focusing on creating a login form project. Despite following the ins ...

What is the process for adding a marker to an Angular Google Map using the autocomplete feature?

Can anyone help me with adding a marker on Google Angular Map using autocomplete search? I am able to retrieve the location in terms of latitude and longitude, but there seems to be an issue with adding the marker. Please review my code below: Controller ...

What is the best way to insert dynamic data into a modal?

I am currently facing an issue with passing a dynamic scope variable into a modal window. The problem arises when I try to update the variable while the modal is open. At present, I send the data to a controller when the modal opens: scope.open = func ...

What is the best way to prevent non-integer input in the last text box?

Currently, I am in the process of developing a JavaScript code. I have included 4 text boxes in the layout that allow only one character to be inputted into each box. An important guideline for this task is that the rightmost field holds the id "first" w ...

The UI Router template fails to inject despite state changes occurring

I've been attempting to create nested views, you can check out the Plunker demo https://embed.plnkr.co/oRMnMW4QoWwhSkm9maHf/. The state is updating as expected but the template remains the same. Could someone please point out where I may have gone wr ...

Error message: Unknown scope- unable to process 'files-path' Android File provider issue

My current project involves implementing file system access in react native Android. However, when attempting to add 'files-path' in XML, an error stating "Error: Unsupported type 'files-path'" is encountered. I am utilizing the react n ...

Error: The method 'send' is not available for the object #<ServerResponse>

So I've been diving into building this Express app and all of a sudden, I run into this strange error message that reads TypeError: Object #<ServerResponse> has no method 'send'. It popped up when I was setting up some routing using th ...

Encountering an error while using JSON.parse

I have just finished writing this code snippet: function getScreenshotObj (pathToFirstFile) { return new Promise ((resolve,reject) =>{ console.log("The path to the temporary directory is: " + pathToFirstFile) fs.readFile(pathToFirst ...

Combining two input text strings

A React component I'm working on takes the user's first and last name to create unique usernames for them. class App extends Component { render() { return ( <div className="App"> First name:<br/> <input ...

Send FormData as JSON object array using ReactStrap Form and Express server

Currently in the process of learning the MERN stack, I find myself navigating through React and Express for the first time. One of my tasks involves utilizing an API that I had previously set up to update JSON data using React. To accomplish this, I' ...

Collaborating with multiple forms and files in PHP using jQuery and AJAX operations

Need help with the title for this question. There are two input fields and buttons in index.php <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST"> <input type="text" class="for ...

issue with dependency between factory and controller

Exploring angular js for the first time and attempting to establish a connection between my controller and factory. Here is the controller: var app = angular.module('app', ['ngRoute']); app.controller('MainViewController&apo ...

Vue automatically clears the INPUT field when disabling it

Have you ever noticed why Vue resets a text input field when it's set to disabled? This behavior is not observed with plain Javascript and also doesn't affect textarea fields. var app = new Vue({ el: '.container', data: { disab ...

Sending text from a Tinymce textarea using Laravel 4.2

I am currently facing an issue with a form that includes a tinymce textarea, allowing users to edit text and save it into a database with HTML tags for display on their profile. The problem arises when Laravel 4.2 escapes the HTML tags, making it difficult ...

Showing just the keys of a JavaScript object array using Angular

Check out this live code example on JSbin Can you show only the key from expression syntax in Angular? Specifically, the key being the word "page". And is it possible to do this from an array (even though they are the same word)? HTML <body ng-app="a ...

Unpredictable order of replies retrieved using $http.get

I am struggling to create a function that sends multiple requests to the server based on the number of Ids in the idArray. The issue I am encountering is that the data being pushed into the dataArray does not align with the corresponding Ids of the idArr ...

Is there a way to reload the page post an ajax request without losing the parameters passed? I'm looking for a partial refresh, not a full

Using AJAX from jQuery, I am working on a page where I display the results of a POST/GET request with specific parameters as filters to the server. Let's say I have provided parameters a&b&c to the user in order to view a subset of data that ...

AngularJS: Customizable URL Prefix for Dynamic Routing

I am facing a challenge with my large Angular app that is currently accessible through the following URL: http://myangularapp.com/app/index.html#/ In order to support multiple users, I need to dynamically inject a name into the URL that I will be sharing ...

Issues encountered with Three.js MeshBasicMaterial functionality

I am currently working on generating a texture using Three.js. The texture_f1 source I am using is a .png file, which allows the background to show through. The issue arises when attempting to set the background color using color: 0xffffff in conjunction ...

Adjust background based on centered website viewport position

My website is currently centered using the traditional container technique with a margin of 0 auto. However, I am trying to figure out how to make my background follow my main div. Is there a way to achieve this effect? Specifically, I want my background ...