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

Executing two Ajax calls in ReactJS with different parameters can improve the efficiency of your

Why does the second Ajax call overwrite the first one, causing the results to be different each time I refresh it? In the first Ajax call, I have set tests: [], testsHistories: [] in the setState function. However, the second Ajax call only sets the stat ...

Experiencing problems with the calling convention in JavaScript

Here is a snapshot of the code provided: If the function testFields at Line:3 returns false, then the program correctly moves to Line:21 and returns the value as false. However, if testFields returns true, the program proceeds to Line:4, but instead of ex ...

What steps are involved in creating a video playlist with YouTube videos?

Is there a way to create a dynamic video playlist that supports embedded YouTube videos without refreshing the page? If a user clicks on another video, I want the video to change dynamically. You can check out this for an example. Do jPlayer, Video.js, Fl ...

In Node.js and Postgresql, encountering the error "Trying to access a property that is undefined" is common and can be frustrating

const pool = new pg.Pool(config); var tablename = req.body.tablename; pool.connect(function (err, client, done) { var query_get_value = 'SELECT * FROM '+ tablename; client.query(query_get_value, function (err, result) { d ...

What is the most efficient method for identifying and modifying an element's in-line style while performing a swipe gesture?

Recently, I've been developing a left swipe gesture handler for chat bubbles. Implementing touchMove and touchStart seems like the logical next step, but for now, I'm focusing on making it work seamlessly for PC/web users. I managed to make it f ...

Transform JSON data into a JavaScript object

There is a JSON string in a specific format: [{"A":"SomeStringData","B":1}, {"A":"SomeStringData","B":2}, ... ... ...] It should be noted that this JSON string passes through all online parsers successfully and is considered valid. An attempt is being ...

My Vuefire firestore() function is failing to properly bind my data

I am encountering a problem that has me stumped. VueFire worked perfectly in another application I developed, but for some reason it is not binding correctly in my current one. Below you can see the code snippet on the page where the firestore() function i ...

I require a way to decelerate the speed of the roulette wheel's rotation

For my assignment, I'm tasked with creating a roulette spin wheel code in JavaScript without using any plugins. I need to incorporate some conditions before executing the code, particularly for slowing down the speed of the roulette spin. Additionally ...

The $scope.$watch function does not activate with each individual change

Yesterday, I realized that in my angularJS 1.4.8 application, the $scope.$watch doesn't trigger on every change causing a bug to occur. Is there a way to make it work on every change immediately? For example, in this code snippet, I want the function ...

The function getattribute() on the edge is malfunctioning and returning a null value

Has anyone encountered issues with the getAttribute() function while creating an extension for Edge? I am currently facing a problem where it is not returning the attributes of the element that I am searching for. This is what my code looks like on Edge a ...

Having trouble accessing the value of a node in JavaScript, as it keeps returning as "null"

Experimenting with converting HTML elements into lists. The objective is to generate a list of all values in a table upon clicking the "page next" buttons on it. Afterward, an alert should display the value of the first item in the list, which corresponds ...

Generate a loop specifically designed to execute the code following the menu in the script

My website has the code snippet below: let txt_com = document.querySelector(".text_user"); let num_com_user = document.querySelector(".massage_for_user"); txt_com.addEventListener("click", function() { if (this.classList.contains("num_com_user")) { ...

Guide on implementing two submission options in an HTML form using JavaScript

Currently, I am working on a form that includes two buttons for saving inputted data to different locations. However, I am facing an issue with the functionality of the form when it comes to submitting the data. Since only one submit function can be activa ...

Learn how to move to a new line when inputting data into a CSV file with JavaScript

My challenge involves taking an array of objects, for example: array=[hello, how, are, you], extracted from the document.innerHTML. I aim to write these objects to a CSV file using puppeteer and JavaScript, each on a new line. Although when using the sta ...

Applying onclick css changes to a specific duplicate div among several others?

Recently, I encountered a situation where I have multiple identical divs on a page. <div class="class" ng-click="example()"></div> With the use of Angular 1.6.4 and jQuery, these divs are styled with background color and border color. Now, w ...

Conceal All Other Divs upon Clicking on a New Div Bearing the Identical Class

I'm having trouble implementing the feature that closes other divs when I click on a new div with the same class. It seems like it should be straightforward, but for some reason, it's not working for me. Here is the link to the fiddle where I&apo ...

Ending the loop of a jQuery JSON array when reaching the final row

I have a function that retrieves a JSON array and shows the results as a list with ten items. However, if there are fewer than ten results, it starts over from the beginning. This is my code: $.ajax({ url: 'http://www.entertainmentcocktail.com/c ...

Struggling with rendering components in REACT?

I'm encountering an issue with rendering the Butcher Shop component. I can't seem to pinpoint what's causing it to be null or undefined. Can someone help me identify the mistake? Nothing is showing up on the DOM and I keep getting this error ...

Efficient initialization process in Vue.js components

Upon initialization of a component, the data callback is executed as follows: data(){ return { name: myNameGetter(), age: myAgeGetter(), // etc... } }, Following that, a notification is sent to a parent component regarding ...

Please input only 0s and 1s into the designated field

How can I modify this code to only accept 0 and 1 in the input field, while also adding spaces after every 4 digits? Currently, it accepts all digits. I'm struggling with creating a pattern that restricts it to just 0 and 1. document.getElementById(&a ...