The layout of a Vuex store in a sprawling website

Currently immersed in the development of a sprawling website using Vue.js, I find myself grappling with the architecture of Vuex store.

The current folder structure is as follows:

.
├── build
├── src
│   └── components
│       ├── Header.vue
│       └── TimeStamp.vue
│       └── Photo.vue
│   └── pages
│       ├── index.vue
│       └── about.vue (includes Header.vue, Thumbnail.vue)
├── store
│   └── index.js
│   └── modules
│       ├── Header.js
│       └── TimeStamp.js
│       └── Photo.js

As it stands, my coding approach is to associate each component with a relevant module store. However, I am facing confusion due to the fact that all module states need to be imported as a single comprehensive object. This poses a challenge because even if a page does not require a certain component such as TimeStamp, its state still lingers within scope. In a scenario where there might be hundreds of states in total, yet only the Header.js store is needed, the rest become redundant.

Hence, my query is:

Is it feasible to create dynamic state objects for each page? For instance, in the About page, only import Header.js and Photo.js, while in the Index page, only incorporate Header.js and TimeStamp.js. The envisioned structure would resemble something like this:

├── store
│   └── pages
│       ├── Index.js
│       └── About.js
│       └── News.js
│
│   └── modules
│       ├── Header.js
│       └── TimeStamp.js
│       └── Photo.js

Answer №1

Managing Module States

It appears that all module states need to be imported as a single, cohesive object.

While it is indeed handled as a unified object, don't forget about the getters that can retrieve specific pieces when needed?

Merging store modules together is incredibly straightforward.

export const store = new Vuex.Store({
  modules: {
    config,
    user,
    pages,
    ...
  },
  plugins: [addTagToType_StorePlugin]
})

The advantage of having a single object is the ability to integrate cross-cutting code like the addTagToType_StorePlugin mentioned above (which enhances developer tools display).


Creating Dynamic State

Can dynamic state objects be generated for each page?

Absolutely.

There are no strict rules regarding how you should organize your state. The flux pattern simply provides guidelines on updating and accessing state.

You should structure your state in whatever way suits your application best.

As shown above, I utilize a pages state module. To illustrate the dynamic aspect, here's an initial structure.

const state = {
  files: {
    validations: [],
    referentials: [],
    clinics: []
  },
}

Each property under files corresponds to a different page. If the user never visits the 'validations' page, the state for that page remains unloaded.


Accessing Dynamic State

Your getter can return a function that accepts a parameter, allowing for the 'dynamic' selection of the state slice (Reference: Vuex Getters).

const getters = {
  pageFiles: state => {
    return page => {
      return state.files[page]
    }
  },

computed: {
  pageFiles() {
    return this.$store.getters.pageFiles(this.page)
  },


Dynamic State and Devtools

The previously mentioned plugin is utilized to enhance the chrome devtools display when manipulating dynamic data (Reference: vue-devtools).

const addTagToType_StorePlugin = store => {
  store.subscribe((mutation, state) => {
    if (mutation.payload.tag) {
      mutation.type = `${mutation.type} / ${mutation.payload.tag}` 
    }
  })
}

The mutation might be SET_FILES, but which page files?
Provide the page type in payload.tag, and this plugin will modify (for example),

SET_FILES

to

SET_FILES / validations

Answer №2

The essence of using the vuex store lies in consolidating all data within a single object. Selectively choosing parts of the store contradicts its original purpose. If you have data that pertains only to a specific page, it is best managed independently rather than at a global level.

In Summary:

Absolutely Not

However, in theory, you could load and unload data as needed when loading components. You may even automate this process, but it deviates from the core concept of the flux pattern.

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

Highlight or unhighlight text using Javascript

Currently, I am facing a challenge in highlighting specific words on an HTML page. Although I have succeeded in highlighting the desired element, I am struggling with unhighlighting the previous word when a new search is conducted. Despite my attempts to i ...

The passport authentication process is currently stalled and failing to provide any results

The current authentication process is functioning properly app.post('/login', passport.authenticate('local-login', { successRedirect: '/home', failureRedirect: '/login', failureFlash: true }) ); Howev ...

Having trouble with the post request in Express JS and Vue? Don't worry, we've got you covered

I've been following a tutorial to set up a basic app and everything is working smoothly, except for the post request which seems to be causing me trouble. Tutorial: https://www.youtube.com/watch?v=HkIGAqAP1GY Although the issue is reproducible based ...

JavaScript array containing objects remains static

I'm facing an issue with a complex array of objects (I will only display the necessary nodes to explain the problem): var arr = [ { json: { doc: { id: 1, atualizacao:{ ...

Problem with loading messages in VueI18n locale

Utilizing the vueI18n package for language localization in our application, we fetch the locale messages object via an api call. Within our config file, we have specified the default language which is used to load the locale before the creation of app.vue. ...

Extracting Unprocessed Data with Node.js Express

I am currently working with an Express server that handles a login form page: const app = express(); // part A app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded()); app.get('/login', ...

The jQuery .Text() method efficiently replaces the contents of an element with fresh

I am experiencing an issue where the .text() function in jQuery replaces both the text and HTML within an element. I'm looking for a solution that allows me to only modify the actual text and leave the HTML intact. Any ideas on how I can achieve this? ...

What could be causing the issue with this basic THREE.js javascript particle system?

{/*I'm not sure if there are any errors in this code. I'm using the latest version of Chrome for testing purposes. Previously, I created a similar program that displayed a wireframe cube without any issues. It ran smoothly at that time. However, ...

How can you efficiently cache a component fetching data from an API periodically in React?

I have a situation where I need to continuously fetch data from an API at intervals because of API limitations. However, I only want to update the state of my component if the API response is different from the previous one. This component serves as the m ...

retrieving XML information into a div using Ajax and JavaScript

I am currently working on developing a chat application and facing an issue with fetching all logged in users into a div with the ID "chat_members". Despite confirming that the XML file structure is correct, the JavaScript code alongside AJAX does not seem ...

changing the RadioButtonList to preselect a default value

On a page, I have a pre-existing RadioButtonList where I want to make the second button checked by default instead of the first one. Since I am unable to edit the original control directly, it seems like I might need to achieve this using javascript on th ...

Retrieving data from Firestore yields an empty result

Having trouble reading from Firestore within a function, even though writes are working fine. Despite following examples on the given link, the query below and its variations result in an empty promise: module.exports.customerByPhone = phone => { r ...

Avoiding the use of apostrophes in jQuery or JavaScript

I need to show the text below for the <span> element. What's the best way to handle single quotes in this case? $("#spn_err").text($('#txt1').attr('value')+" is not valid"); The desired message format is 'ZZZ' is ...

Express Producing Empty Axios Post Request Body

I am facing an issue with sending two text data pieces from my React frontend to an Express backend. Whenever I use the post command with Axios, the body appears as {} in the backend and becomes unusable. Below is the code that I am using. Client (App.js) ...

angularJS transformRequest for a specified API call

Looking for a way to pass multipart/formdata through a $resource in Angular so I can post an image. I discovered a helpful solution on this Stack Overflow thread. However, the solution applies to all requests within my modules, and I only want it to apply ...

React's input onChange event does not trigger for the second time. It only works the first time

Recently, I developed a React JS application to import images from external sources and process them. To handle the user's onChange event, I utilized the onChange attribute to execute my handleChange function. However, I encountered an issue where it ...

Formik's handleChange function is causing an error stating "TypeError: null is not an object (evaluating '_a.type')" specifically when used in conjunction with the onChange event in DateInput

When using the handleChange function from Formik with the DateInput component in "semantic-ui-calendar-react", I encountered an error upon selecting a date. https://i.stack.imgur.com/l56hP.jpg shows the console output related to the error. AddWishlistFor ...

``on click of the back button of the browser, automatically submit the form

I'm facing a specific issue that I need help with. I have created a form with a hidden value, and I want it to be submitted when the user clicks the browser's back button. Although I've managed to control the backspace key, I haven't be ...

The attempt to create the property 'and_ff' on the string 'and_chr 89' has failed

Encountering an issue with a Lambda function, I receive an error that does not occur when running the same code within an Express app. I'm puzzled. Data returned by caniuse.getLatestStableBrowsers(); [ 'and_chr 89', 'and_ff 86& ...

Showcasing the information stored within my li element, I am able to access and view the data through my console

I want to showcase the data in the browser Upon hitting the api call, I retrieve the data in my console. The challenge lies in displaying the data within my li tag. Below are snippets of my relevant code and the entire code can be found in the gist links p ...