What is the best method for saving inert data in Vuex?

Once the VueJS application is initialized, I have certain data loaded on the page that will remain static until the HTML page is reloaded. This data is in the form of a nonReactiveObjectWithSomeNestedData example:

const nonReactiveObjectWithSomeNestedData = { 
  a: 'a',
  b: {
    bb: 'bb',
    cc: { ccc: 'ccc' },
    dd: ['dd1', 'dd2']
  }
}

This data is used in multiple Vue components and it would be convenient to store it in a Vuex namespaced module and utilize Vuex getters to wrap the same functionality for different components. Is there a way to store this data outside of the Vuex state (without reactivity) but still be able to access it from a Vuex module's getter?

PS. Currently, I am storing non-reactive data inside a Vue instance method. However, I now require more global access to the data from two independent root components.

Answer №1

Make sure to freeze the object first before adding it to the store:

Object.freeze(nonReactiveObjectWithSomeNestedData )

Vue does not add reactivity to frozen objects.

Please remember: Freeze the object before passing it to a Vuex mutation/action:

this.$store.dispatch('moduleName/setNonReactiveObject', 
    Object.freeze(nonReactiveObjectWithSomeNestedData));

Within the mutation function, the payload parameter will already be reactive.

Answer №2

Another way to prevent an object from becoming reactive is by adding a property _isVue to it.

commit('setNonReactiveObject', Object.assign(data, { _isVue: true })

This method can come in handy when you need to maintain non-reactive data, especially in situations where you don't have control over how data is stored in the store. For instance, when replacing all store data on the client-side to match a server-side rendered website (e.g. Nuxt).

Although not officially documented, this approach may not work in the future. The source code has comments suggesting that this property is used internally for this purpose. Furthermore, the property is checked before object observation takes place.

Answer №3

To eliminate the reactivity, I utilized the following approach:

// A new variable is created to eliminate reactivity, by performing a deep clone
var nonReactiveClone = JSON.parse(JSON.stringify(originalReactiveVariable));

Answer №4

When working with mutation files, remember to deep clone the payload for non-reactive properties.

import _ from 'lodash';

    [mutationTypes.SET_INITIAL_STATE](state, payload) {
    // To ensure non-reactivity, deep clone the property
    state.initialState = _.cloneDeep(payload)
}

By following this approach, the added property in the state will remain non-reactive.

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

Dropping anchor whilst skipping or jumping

One of my website elements is a drop anchor that connects from a downwards arrow situated at the bottom of a full-page parallax image to another section on the same page. The HTML code snippet for the drop anchor is as follows: <section id="first" cla ...

Transferring data from JavaScript to ASP.NET (via AJAX)

I'm trying to figure out how to pass variables from JavaScript to a textbox. I have a variable in JavaScript but I am unsure how to transfer it to the textbox. I have heard that using AJAX makes it easy, but I don't know how to implement it. I th ...

How to Load JSON Data Using D3 When Column Definitions are Separated

I'm currently working with d3.js and struggling to grasp how I can effectively load a JSON file representing a table that has separate column definitions. A typical JSON file, which I have no issue loading, might appear like this: [ { "id": 1, ...

How can I change the background image using CSS instead of HTML?

I initially created a non-responsive website for an existing project. Now I need to convert it into a responsive site. I tried changing the logo image to make it responsive, but it's not working as expected. <td colspan="2" style="background-image ...

Validate if the translation file exists in ngx-translate

Is there a way to determine if a translation file exists for the language obtained from navigator.language using ngx-translate? I am looking to implement something similar to: if( isLanguageAvailable(navigator.language)) { this.translate.use(navigator.l ...

Vue's unshift method only appends new items to the beginning of an

Could you help me with a problem similar to this one: The array I am working with looks like this: remate: {id:1, lotes: [{id:1, nombre: lalala}, {id:2, nombre: lololo}]} My issue arises when attempting to add new items to remate.lotes. While the push m ...

Trimming Picture on User's Device

Currently, I am utilizing the jQuery ImgAreaSelect 0.9.10 plugin to crop images that are uploaded by users. The data input format being used is "multipart/form-data". Upon cropping an image with the plugin, it provides me with coordinates in pixels. Howev ...

Error Message for Sequelize Validation Fails to Appear as Expected

I am trying to implement Sequelize model validation in order to validate a form field. When the book or author fields are left empty, I want this message to be displayed: Oops! An error occurred. "Title" is required. "Author" is required. The issue I&ap ...

How come the mouseover effect on the div remains even after the mouse has been removed?

How can I keep the original CSS class when the mouse moves away? function highlight( x, y) { var sel=document.getElementById(y); sel.style.borderBottom= "2px solid "+x; sel.style.opacity="1"; sel.style.transition="all eas ...

Tips on skipping the need to repeatedly use `@ApiProperty()` for every dto in NestJs-swagger

I'm currently exploring ways to streamline the process of specifying @ApiProperty() for each DTO. I've heard about a method involving the creation of a nest-cli.json file, where if you define Promise<DTO> in your controller within nest-swa ...

What could be the reason for the absence of an option in the navbar

As I work on creating a navbar menu that functions as an accordion on desktop and mobile, I encountered an issue. When I click on the dropdown on mobile, it displays one less item than intended. This seems to be related to a design error where the first it ...

Repeated information displayed in modal pop-ups

HTML <a class="btn" data-popup-open="popup-1" href="#">More Details</a> <div class="popup" data-popup="popup-1"> <div class="popup-inner"> <h2>Unbelievable! Check this Out! (Popup #1)</h2> ...

Modifying a JavaScript code with document.write(variable)

I am working with a Javascript function function setComparison(data) { var w= window.open('', 'comparison', 'width=600, height=400'); w.document.open(); w.document.write(getComparisonContent(data)); w.document ...

Reloading a page in Vue-Router after submitting a form

Learning Vue by creating a movie searcher has been quite challenging. The issue I'm facing is that I'm using the same component for different routes with path params to fetch specific information. However, when I submit a form with a query for t ...

Preserve final variable state - Angular

My function looks like this: flag: boolean = false; some_function(){ var foo = some_num_value; var bar = foo; // Storing value in a separate variable if(this.flag){ v ...

What is the reason for the lack of arguments being passed to this Express middleware function?

I have been developing a middleware that requires the use of `bodyParser` to function, however I do not want to directly incorporate it as a dependency in my application. Instead, I aim to create a package that includes this requirement and exports a middl ...

Converting Strings to Booleans in Vue: A Dilemma

Within my Vue HTML code, I have the following: <v-textarea auto-grow="true"></v-textarea> The functionality works as intended, with the textarea expanding automatically. However, it does trigger an error message: [Vue warn]: Invalid ...

"Function.click operates successfully when no arguments are given, but encounters issues when arguments are supplied

I had a function that was functioning correctly: $('#buttFurniture').click(onFilterCLick); However, when I decided to pass arguments to the function, it stopped working: $('#buttFurniture').click(onFilterCLick(arrOutput, arrFurniture ...

JQuery receives an enchanting response from the magic line

I could really use some assistance with this problem. I've managed to make some progress but now I'm stuck! Admittedly, my JQuery skills are not that great! Currently, I have a magic line set up where the .slide functionality is triggered by cli ...

Issue with emitting events from child to parent component

<div @ontabselected="sayHelloFromRoot"> <tabs> <tab></tab> <tab></tab> </tabs> </div> I have set up an event listener called ontabselected in the Tabs component and I'm emitting ...