Uncover the underlying reasoning within the Vuex state

Struggling to find the right way to structure my Vuex store for a particular issue.

In my store, I have an array of buttons or actions, totaling in the hundreds. Here's how they are currently organized:

buttons: [
  {
    text: 'Button 1',
    doAction (store) {},
    mustShow (store) {
      return state.variable > 10 && state.variable2.counter < 12 && !state.variable3
    }
  }
  ...
]

Displaying them in the view and linking their actions to the click event is a breeze:

<button v-for"button in buttons" @click="button.doAction()"></button>

The challenge lies in the fact that each button's visibility is determined by complex, unique logic within its mustShow function. Each button has its own distinct criteria.

To only show buttons that meet their display criteria, I can create a getter like this:

availableActions (state) {
    return state.buttons.filter(s => s.mustShow())
}

Although this solution works initially, the problem arises when the getter is non-reactive because it's tied to the result of a function rather than reactive state variables.

How should I reorganize the code to address this issue? While consolidating all button display logic into a single getter is an option, what if I also need the button names to be dynamic based on certain state variables?

Your insights would be greatly appreciated. Thank you.

Answer №1

It seems like you might be headed in the wrong direction with this approach. As a general rule of thumb, it's not recommended to have complex objects, such as function definitions, defining your store state. The store state should be something that can be easily encoded in JSON, shared with others, and produce the same results when used in the same program. Having a function inside the state would not align with this principle.

My suggestion would be to structure your store state like this:

const state = {
  buttons: [
  {
    text: 'Button 1',
    id: 1
  },
  ...
  ]
}
...
const actions = {
  doAction ({commit}, {btnId}) {
   // Perform the desired action here
   ...
   // To update the store state, commit a mutation instead of changing the state directly
   const payload = { btnId }   
   commit(changeSomethingInState, { payload })   
  }
}

const mutations = {
  changeSomethingInState (state, { payload }) {
    state.something = payload
}
...

This setup is for the store definition. In your view, you can use the following code:

<button v-for"button in buttons" @click="dispatch('doAction', { btnId: button.id })"/>

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

What are the challenges associated with using replaceChild?

function getLatestVideos(url) { var http = new XMLHttpRequest(); http.open("GET", url, false); // false for synchronous request http.send(null); return http.responseText; } var videosText = getLatestVideos("https://www.googleapis.com/youtube/v3/se ...

Customize the drawer background in Vue Material

Recently, I developed a vuejs application incorporating Google's material design components. I've been exploring options to customize the background color. <template> <div class="page-container"> <md-app> ...

What is the best way to combine and merge JSON objects that consist of multiple sub-objects?

I am working with a JSON response that contains multiple objects consisting of two main objects - datacenter and environment: "deployments": [ { "datacenter": { "title": "euw1", ...

Do you require assistance with creating an image slideshow?

My first day working with HTML was a success as I successfully built a navigation bar that looks pretty cool. Take a look at it here. Next on my list is to incorporate a slideshow into my site, possibly using JavaScript or jQuery plugins. I'm aiming ...

Utilize a function as a parameter

I am struggling to figure out how to make this function pass by reference in my code. Is there a way to achieve this? var Class = function() { var callback1; var callback2; function buildStuff(data, callback) { element.onclick = funct ...

What's the most effective method for handling routes and receiving parameters in ExpressJS?

I have created a unique Express.js system where each file in the /routes folder serves as a separate route for my application. For example, /routes/get/user.js can be accessed using http://localhost:8080/user (the /get denotes the method). You can view m ...

What steps should I take to show a particular set of data upon selecting a checkbox component?

I have a table with a column named status, which can be in progress, pending, or dispensed. https://i.sstatic.net/1mMNQ.png My goal is to filter the data based on the checkbox that is selected above the table. For instance, if I check the "pending" check ...

Empty input fields in Javascript calculations will result in a NaN output

I need to perform a calculation using values entered into form fields and JavaScript. The formula I'll be using is as follows: totalEarnings = income1 + income2 * 0.7 + income3 / 48 + (income4 * 0.7) / 48; The variables income1, income2, income3, an ...

PHP - Unable to verify session during script execution

I'm currently working on a PHP script with a lengthy execution time, and I am looking for a way to update the client on the progress of the script. Since the script is invoked via AJAX, output buffering is not a feasible option (and I prefer to keep ...

Is there a way to imitate a method that initiates an AJAX request?

I am currently working on writing tests for my Angular application and I need to mock a method in order to avoid making actual requests to the server. Within my grid.service.ts file, here is the method I am trying to mock: loadAccountListPromise(id: str ...

Retrieve the file for saving using the HttpPost method in Asp.Net MVC

In my Asp.Net MVC project, there is a page where users can edit data loaded into a table, such as changing images, strings, and the order of items. Once all edits have been made, the client clicks on a Download button to save the resulting xml-file on the ...

What is the process of transferring a file to the server side as byte code in Vue.js?

My current challenge involves transferring an attached file from the client-side to the server-side. I have attempted a couple of methods to retrieve the file, as outlined below: 1) var files = event.target.files; var file = files[0]; 2) var image ...

NodeJS Streams: Delay in data transfer with Readable.pipe()

My understanding was that Stream.Readable.pipe() would immediately pipe data as it receives it, but I'm facing unexpected results while trying to create my own streams. const { Writable, Readable } = require("stream"); const writable = new ...

Having trouble adding/removing/toggling an element class within a Vue directive?

A successful demonstration can be found at: https://jsfiddle.net/hxyv40ra However, when attempting to incorporate this code within a Vue directive, the button event triggers and the console indicates that the class is removed, yet there is no visual chang ...

When the button is clicked, request the total count of elements in the array

Is there a way to log the index of an array element when clicked? I have a large array with over 100 elements: var cubesmixed = []; var cubes; for(var i = 0; i < 143; i++) { cubes = paper.rect(Math.floor(Math.random()*2000), Math.floor(Math.random ...

Discovering the method to incorporate a data-icon attribute within select options using vue.js

UPDATE before modification dataIcon: " @/images/flag-ukraine.svg" after modification dataIcon: require("@/assets/svg/flag-ukraine.svg"), notable change with require() I am using Materialize CSS select. When I use a URL for dataIcon ...

Is there a way to asynchronously load image src URLs in Vue.js?

Why is the image URL printing in console but not rendering to src attribute? Is there a way to achieve this using async and await in Vue.js? <div v-for="(data, key) in imgURL" :key="key"> <img :src= "fetchImage(data)" /> </div> The i ...

The system encountered an error while trying to access the file "/box/main.c" because it does not exist in the directory

Currently, I am working on a project that requires the use of judge0 API. Initially, everything was running smoothly when I utilized it with RapidAPI. However, I made the decision to switch to a self-hosted setup using a docker-compose.yml file. While my ...

Enhance the database with partial updates using the patch method in Django Rest Framework

I have a model called CustomUser that extends the AbstractUser class. class CustomUser(AbstractUser): detail = models.JSONField(default=dict) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=Tr ...

Enhancing User Experience with Load Indicator during State Changes in React Native

I'm facing an issue where the page for displaying a single item is loading slowly - I need to delay the page from loading until the object has changed. After checking the navigation params through console log, I can see that the id changes when each b ...