Learn the art of altering Vuex store values dynamically

I have been exploring ways to utilize Vue.set() to dynamically modify bound data within Vuex store. After some trial and error, I came up with a solution that has been working for me. Please note that the code may not be the most elegant.

This is my current solution:

  mutations: {
    add_to_store(state, [route, key, value]){
      const call_vue_set_with_dynamic_params = new Function(
        "Vue",
        "state",
        "route",
        "key",
        "value",
        `Vue.set(state${route === "" ? "" : `.${route}`}, key, value)`
      );

      call_vue_set_with_dynamic_params(Vue, state, route, key, value)
    }
  }

If anyone has some time to spare, it might be interesting to try and optimize this code further as I am currently feeling a bit stuck. I attempted to pass the found object into Vue.set() like this:

const create_nested_object = ( base, names ) => {
  names.split(".").forEach(name => {
    base = base[ name ] = base[ name ] || {}
  })
  return base
}

mutations: {
  add_to_store(state, [route, key, value]){  
    Vue.set(
      create_nested_object(state, route),
      key,
      value
    )
  }
}

Unfortunately, this approach did not work as expected. I also experimented with overwriting the entire state with a new one, but this caused reactivity issues.

The ultimate goal of this mutation is to take a string specifying the route to the desired object like: user.hair.color and update it with the desired value. The intention is to avoid creating separate mutations for each key individually.

Answer №1

Although untested, this method is expected to function properly. By iterating through the route keys and maintaining a reference of the deeply nested object, you can then pass it to the Vue.set method.

const get_nested_object = ( base, names ) => {
  let ref = base
  names.split('.').forEach(name => {
    ref = ref[name]
  })

  return ref
}

mutations: {
  update_state(state, [route, key, value]){
    Vue.set(
      get_nested_object(state, route),
      key,
      value
    )
  }
}

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

Javascript - Could anyone provide a detailed explanation of the functionality of this code snippet?

Ever since joining a new company 9 months ago, I've been encountering this line of code in JavaScript. It seems to work fine and I've been incorporating it into my coding style to align with the previous developers. However, I'm not entirely ...

When importing the Ionic Native File, the JavaScript File object cannot be used simultaneously

When attempting to use the javascript file object, I encountered an issue because the ionic native file object already uses the same key File Here is an example: import { File } from '@ionic-native/file'; @Component({ selector: 'page-ho ...

javascript - Utilizing the latest ES6 syntax

During my exploration of the source code for an open source project (react data grid), I came across a syntax that left me puzzled: class EditorBase extends React.Component { getStyle(): {width: string} { return { width: '100%' ...

What is the best way to overlay text onto a background image using Material UI's Card and CardMedia components?

Using the card component, I have successfully added a background image. However, I am facing difficulty in figuring out how to overlay text on top of this image. If anyone has suggestions or alternative methods, please feel free to share! <Card> ...

Excel-like JSON Data Grid using jQuery

I am in need of a data grid similar to an Excel sheet. My primary focus is on filtering capabilities only (refer to the image below). Can anyone offer assistance with this? ...

Renew the id_token in the front-end: Angular 4

I am currently utilizing the ng2-adal npm library to create id_token and access_token. As the id_token is valid for 30 minutes and the access_token for 60 minutes, my goal is to automatically refresh the id_token every 20 minutes in the background. One pot ...

Sharing a boolean state between two pages using Material UI components

One challenge I've been facing is passing a boolean useState value between two pages. I found a helpful solution on this Stack Overflow thread: How to call useState from another Page? The main goal here is to display a success alert on a separate pag ...

Strange Puppeteer conduct

Currently, I am utilizing Puppeteer to launch a headless web browser and interact with a specific website using JavaScript. The website requires login credentials before proceeding further. Upon login, a popup window appears which closes once the authentic ...

The postman is coming back empty-handed with a 200 status code

I am receiving a null value as a response with a 200 status code. I am expecting to see the profile details as the response, but instead it is showing a null value with no error status code in my Postman. I can't find any errors in my code. Why is it ...

Color buffer can cause WebGL rendering to fail

<!DOCTYPE html> <html> <body> <canvas id="ctx" width="300" height="300"></canvas> <script> //Receiving Webgl Context var ctx = document.getElementById("ctx"); var webgl = ctx.getContext("exp ...

Creating a custom component results in an extended duration to 'eliminate' its children

1I am currently facing an issue with a time-table component created using vue.js. It contains approximately 200 nested child timeline components, making it quite complex (I wanted to share an image but lacked the reputation to do so). The main problem lie ...

Progressive rendering of a substantial mesh using three.js

How can I efficiently render a large static mesh in three.js, even if it's 2 GB with tens of millions of polygons? My plan is to stream the mesh geometry buffers into indexedDB and render them progressively to the screen, all while maintaining an int ...

Accessing a single element from a nested object in Handlebars.js

Recently, I have been working on a nodejs application that utilizes handlebars js as its view engine. My main challenge at the moment is accessing one specific element from a nested object that I am passing to the hbs view. router.get('/view_users/:i ...

Mongoose: Imposing Requirements on Optional Fields

I have a Mongoose Schema setup like this: const PostSchema = new mongoose.Schema({ title: { type: String, required: true, }, content: { type: String, required: true, }, ...

Tips for setting up Craigslist email forwarding through Node.js (receiving emails to a dynamically generated email address and redirecting them)

After extensive searching, I only came across this Stack Overflow post about Email Forwarding like Craigslist in Rails: Email Forwarding like Craigslist - Rails I spent a significant amount of time googling, but couldn't find any solutions using Node ...

Obtain the visual representation of an object created in three.js during the rendering process

I have been pondering the way in which three.js handles rendering. It seems to me that it converts each element into an image before drawing it on a context. I'm curious if there are resources available where I can learn more about this process. Addit ...

Reverting a concealed segment

Can anyone make sense of my unconventional explanation? I've set up a hidden section as shown below: <section class="intro"> <label> <input type="checkbox"> <span class="menu"> <span class="hamburger"></span&g ...

Learn how to toggle the visibility of a gif image with a button click in an ASP.NET application

I am working on an asp page that includes a button. When the button is clicked, I need to display a gif image. Once the process is complete, the image should be hidden again. Here is the code behind: <head runat="server"> <title>Untitled ...

increasing the size of an element while keeping its overflow hidden

Is it possible to expand an element with "overflow: hidden" when clicked without affecting other elements? I'm looking for a solution that allows the expanded element to overlap and hide the element below it, rather than pushing it down. I've tr ...

Customize the border width and color of a specific column in HighCharts based on dynamic data

I am looking to dynamically change the border width and color of only one column in a basic column chart. Here is an example: var chartingOptions = { chart: { renderTo: 'container', type: 'column' }, xAxis: { categories: [ ...