What is the best way to create a non-reactive value in Vue.js?

In my Vue.js app, I am facing an issue where an array value is becoming reactive even though I want it to remain un-reactive. The array should only be updated when a specific "refresh" action is completed. However, every time a new value is assigned to the array, it immediately changes in reaction to the data in the assigned value.

For instance, let's say I have a method called refresh(). This method is supposed to update displayedData (which should not be reactive) with the data from currentData (which should be reactive). The goal is to have displayedData only update when the refresh method is called.

methods: {
    refresh: function() {
        this.displayedData = this.currentData;
    }
}

Answer №1

To prevent reactivity without making a value static, you can create a "deep copy" using the stucturedClone() method, which has universal support as of early 2022:

this.displayedData = structuredClone(this.currentData);

Prior to structuredClone(), a common method used involved encoding and decoding with JSON:

this.displayedData = JSON.parse(JSON.stringify(this.currentData));

Both approaches copy the current state of one value to another, ensuring that changes to the original value do not affect the copied value until this code is executed again. Nonetheless, structeredClone() is preferable for various reasons.

The need for this process is not unique to Vue.js but stems from the nature of JavaScript. In JavaScript, arrays and objects are "passed by reference" rather than "passed by value".

Answer №3

One way to approach this issue without turning off reactivity is to create a separate array for temporary data and transfer the contents to the main array when the user refreshes the page.

To achieve this, you can simply copy the values from the main array to the temporary array using the following code:

this.temp = this.permanent.slice()
within the created or mounted life-cycle function.

Keep in mind that using the slice method creates a shallow copy of the array. If you also need to clone the items within the array, consider using a deep copy library or the JSON.parse(JSON.stringify(...)) method.

Answer №4

Not adding the currentData to the data() method will result in it not being reactive.

export default {
    currentData: [],
    data() {
        return {

        }
    },
    methods: {
        refresh: function() {
            this.displayedData = this.currentData;
        }
    }
}

To still access currentData in the section, you can use {{ $options.currentData }}

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

Vue.js not responding to "mousedown.left" event listener

I am trying to assign different functionalities to right and left click on my custom element. Within the original code, I have set up event listeners for mouse clicks in the element file: container.addEventListener("mousedown", startDrag); conta ...

Analyzing Dynamic Content

Currently, I am engaged in content parsing and have successfully executed a sample program. To demonstrate, I have utilized a mock link which you can access below: Alternatively, you can click on this link: Click Here In the provided link, I have parsed ...

Enhancing user experience with AngularJS: Harnessing ng-Click for seamless task management on display pages

I'm struggling with my TodoList in AngularJS. I need help creating the ngClick function for the "addTodo" button. My goal is to send the entire form data to another page where I can display the tasks. Can someone guide me on what needs to be added to ...

Setting up Laravel Echo and Pusher-JS in a VueJS application

I'm currently utilizing laravel-echo and pusher-js in a project that combines Laravel and VueJS, and it's functioning well. However, I now face the challenge of broadcasting in a pure VueJS project without any dependency on Laravel. I am uncert ...

Utilizing jQuery time intervals within a jQuery click event: A step-by-step guide

For my dropdown menu project, I am facing an issue where the menu bar is not reappearing after collapsing the dropdown. It seems that the jQuery function responsible for toggling classes within a time interval is not executing properly. Specifically, the " ...

Localization for Timeago JS Plugin

Currently, I have integrated the jQuery TimeAgo plugin into my project and included the following code snippet for localization in Portuguese: // Portuguese jQuery.timeago.settings.strings = { suffixAgo: "atrás", suffixFromNow: "a partir de agora", ...

deleting a aircraft upon the addition of another in three.js

I am striving to implement a button that toggles between different terrain-generating functions and removes the previous terrain. The current issue I am facing is that the planes stack on top of each other. You can see an image of the problem here. There ...

Distinguishing Between CORS and JWT: Understand the Variances

After successfully developing and deploying a Django REST API on Heroku, I encountered an issue when trying to fetch the API in Vue CLI. I received a CORS error message, prompting some questions to arise: Should I enable CORS in the backend using a CORS ...

Can we use ToggleClass to animate elements using jQuery?

I have a section on my website where I want to implement an expand feature. I am currently using jQuery's toggleClass function to achieve this effect. jQuery('.menux').click(function() { jQuery(this).toggleClass('is-active&a ...

Challenges arise when adjusting frame size for mobile and desktop devices

I am trying to achieve an auto-resize feature for my frame's height when the screen width is smaller than a certain value. I want it to behave like Sketchfab, as demonstrated in this video: http://www.youtube.com/watch?v=_y5ckVFGHKU&feature=youtu. ...

Using JavaScript, include a child class into a parent class

I am facing an issue with my class hierarchy, which includes classes like Parent, Child1 (which extends Parent), and Child2. Parent contains an array of child items, but importing Child1 and Child2 into Parent leads to circular dependencies and errors whe ...

Keep your filter content up-to-date with real-time updates in Vue.js

I am facing an issue with a markdown filter where the content of component.doc is set to update through a websocket. Despite updating the scope's component, the filtered content remains unchanged. Is there a way to dynamically refresh the v-html in t ...

Learn to effectively incorporate intersection observer polyfill with Vue cli 3 in your projects

Is it better to include the IntersectionObserver polyfill in a webpack config like vue.config.js, or should I load it directly in a .vue template using imports? ...

Load content within the DIV container

I need help finding code that can use JQuery to load a page into a DIV element. Essentially, I want to load displaycatch.php into a specific DIV <div id="results">Content for id "results" Goes Here</div> Furthermore, I would like to add a ...

Tips for saving information from a textarea into an HTML file

I have a unique question regarding the usage of $fopen and $fwrite functions. My goal is to include a button named "save as HTML" below a textarea. Upon clicking this button, I want a popup box to appear mimicking the 'save as...' dialog window ...

(vue router) What is the most efficient way to avoid code repetition when setting up two routes that share a nearly identical view?

My NewArticleView vue component is linked to the URL path /articles/new. Here's how it's set up: const routes = [ ... { path: '/articles/new', name: 'New Article', component: NewArticleView ...

switchMap: Triggering multiple requests simultaneously (2)

Currently, I am utilizing Angular 2 RC-4 and facing an issue where a network request is being triggered twice whenever there is a change in the input box. This is what my code looks like: component.ts this.term = new Control(); this.suggestions = this. ...

The system encountered an issue regarding a missing dependency: Warning from chokidar (C:): Error: EBUSY: resource busy or locked, unable to access 'C:hiberfil.sys'

While working with Vue, I encountered an error after running npm run serve. Here is the screenshot of the error: https://i.sstatic.net/T55Uw.png Does anyone have suggestions on how to resolve this issue? ...

Ways to activate a stylish pop-up box using an input field (when focus is removed)

While attempting to activate Fancybox upon the user shifting focus away from an input field containing a value greater than 25, everything seems to be in order with the focus out and value checking code. Nevertheless, when Fancybox is triggered, the follow ...

Utilizing the static folder feature in Express on a shared hosting platform

Struggling with implementing a static folder in my Node.js+Express application, I keep encountering a frustrating 404 error. After setting up the basic structure using express project_name, here is the simplified folder layout: app.js /views \-- la ...