Deciphering the intricacies of VUEX-STORE modules

Consider this scenario: I have two separate lists - one for income and one for outcome. Each list has its own storage, and I am adding these storages as modules in index.js.

While I could create a single repository for both income and outcome, displaying them in a list and calculating the total, I prefer to have separate stores for each. This raises the question: How can I implement this correctly?

My current implementation only focuses on INCOME. How can I enhance it to show and calculate both INCOME and OUTCOME in a single component and list?

Should I import both storages using ...mapGetters in one component to calculate and display the total? Or should I retrieve data from both storages, perform calculations in index.js, and then access the computed data from there? How can I effectively utilize multiple modules in a single component to show the balance of income and outcome?

index.js

import Vue from "vue";
import Vuex from "vuex";
import income from "./modules/income";
import outcome from "./modules/outcome";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {},
  mutations: {},
  actions: {},
  modules: {
    income,
    outcome,
  },
});

income.js

import Vue from "vue";

const income = {
  namespaced: true,
  state: {
    list: {
      1: {
        type: "INCOME",
        value: 100,
        comment: "Some comment",
        id: 1,
      },
    },
  },
  getters: {
    incomeList: ({ list }) => list,
  },
  mutations: {
 
  },
  actions: {
 
    },
  },
};

export default income;

outcome.js

// import Vue from "vue";

const outcome = {
  namespaced: true,
  state: {
    list: {
      1: {
        type: "OUTCOME",
        value: -50,
        comment: "Some outcome comment",
        id: 2,
      },
    },
  },
  getters: {
    outcomeList: ({ list }) => list,
  },
  mutations: {

  },
  actions: {

  },
};

export default outcome;

This is the component where I calculate the balance

<template>
  <div class="total-value" :style="balanceColor">
    Balance: {{ totalBalance }}
  </div>
</template>

<script>
import {mapGetters} from 'vuex';

export default {
  name: 'TBalance',

  computed: {
    balanceColor: function() {
      return {
        color: this.totalBalance === 0 ? 'black' : this.totalBalance > 0 ? 'green' : 'red'
      }
    },
    totalBalance() {
      return Object.values(this.incomeList).reduce((acc, item) =>  acc + item.value, 0)
    },
    ...mapGetters("income", ["incomeList"]),
  },
  methods: {

  }
}
</script>

Answer №1

Here is a suggestion for utilizing the store with modules more effectively.

I have also integrated the calculation into the getter, which enhances the cleanliness of your component. Consider transferring the logic to the store to access the balance amount from anywhere in your application.

index.js

import Vue from "vue";
import Vuex from "vuex";
import income from "./modules/income";
import outcome from "./modules/outcome";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {},
  mutations: {},
  actions: {},
  modules: {
    income,
    outcome,
  },
});

income.js

const income = {
  namespaced: true,
  state: {
    list: {
      1: {
        type: "INCOME",
        value: 100,
        comment: "Some comment",
        id: 1,
      },
    },
  },
  getters: {
    incomeBalance: state => {
      return Object.values(state.list).reduce((acc, item) => acc + item.value, 0);
    },
  },
};

export default income;

outcome.js

const outcome = {
  namespaced: true,
  state: {
    list: {
      1: {
        type: "OUTCOME",
        value: -50,
        comment: "Some outcome comment",
        id: 2,
      },
    },
  },
  getters: {
    outcomeBalance: state => {
      return Object.values(state.list).reduce((acc, item) => acc + item.value, 0);
    },
  },
};

export default outcome;

This is your component

<template>
  <div class="total-value" :style="balanceColor">Balance: {{ incomeBalance }}</div>
</template>

<script>
  import { mapGetters, mapState } from 'vuex';

  export default {
    name: 'TBalance',
    computed: {
      ...mapState('outcome', ['list']),
      ...mapState('income', ['list']),
      ...mapGetters('outcome', ['outcomeBalance']),
      ...mapGetters('income', ['incomeBalance']),
      balanceColor() {
        return {
          color: this.incomeBalance === 0 ? 'black' : this.incomeBalance > 0 ? 'green' : 'red',
        };
      },
    },
    methods: {},
  };
</script>

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

Having difficulty creating a file labeled as "undefined" within the grunt plugin

As a newcomer to writing grunt plugins, I've encountered an issue when attempting to run it: Running "inject_css:dev" (inject_css) task Warning: Unable to write "undefined" file (Error code: undefined). Use --force to continue. The structure of my p ...

Material-UI icons refusing to show up on the display

I've been working on creating a sidebar component and importing various icons to enhance the UI, but for some reason they are not displaying on the screen. I even tried other suggested solutions without success. <SidebarOption Icon = {InsertComment ...

Showing various divisions based on the selected option from a dropdown menu

My goal is to have forms display below a select tag based on the number selected by the user. I am attempting to achieve this using JQuery, but it's currently not functioning as expected: Select tag:- <label>How many credit cards do you have:* ...

The upload directory fails to include the folder name when sending a file

After experimenting with the new directory upload feature, I encountered an issue where the server request did not preserve the exact folder structure as expected. Here is the HTML code snippet: <form action="http://localhost:3000/" method="post" enct ...

"Adjusting the position of series data container in Highcharts JS to optimize

Currently, I am utilizing highcharts along with highcharts-ng. My goal is to adjust the position of the container for series Data (where the number 80 is displayed below) slightly higher as it is currently overlapping with the numbers 200 and -200 in the t ...

Vue: The best method to incrementally update properties within props

I am in the process of developing a component that will update props with values retrieved from local storage. These props consist of objects with multiple boolean properties, such as this.globalStates.repeat = false. As I have more than one prop to update ...

What is the best way to determine whether a YouTube video permits embedded playback?

When working with user-generated content, it's important to note that YouTube channels may restrict their videos from being played in an embedded player. In order to provide a better user experience, I need to detect the specific reason why a video ca ...

Send the td value to a PHP script with the help of JavaScript

I have an HTML table that displays records from a database. Below is a screenshot of my table There is a button in a TD (i.e column 5,7,9), when I click the button I want to perform a function to display a popup box with an HTML table. Before that, I wa ...

The application suddenly displays a blank white screen after encapsulating my layout with a context provider

Here is the custom layout I created: export const metadata = { title: "Web App", description: "First Project in Next.js", }; export default function CustomLayout({ children }) { return ( <html lang="en"> ...

What are some strategies for optimizing speed and efficiency when utilizing jQuery hover?

While developing a web application, I have created a grid using multiple div elements that are X by Y in size, determined by user input. My goal is to change the background color of surrounding divs within a certain distance when hovering over one particul ...

Capturing mouse clicks in Javascript: a guide to detecting when the mouse moves between mousedown and mouseup events

I have been working on a website that features a scrolling JavaScript timeline, inspired by the code found in this tutorial. You can check out the demo for this tutorial here. One issue I've encountered is when a user attempts to drag the timeline an ...

Map on leaflet not showing up

I followed the tutorial at http://leafletjs.com/examples/quick-start/ as instructed. After downloading the css and js files to my local directory, I expected to see a map but all I get is a gray background. Can anyone advise me on what might be missing? T ...

``There seems to be an issue with setting the input value attribute using jQuery's .html

I've been trying to update the value attribute in the input element within my HTML code, but so far, I haven't had any luck with it. HTML: <div class='photo-info'> Photo Name : <span class='photo-name'><?p ...

Guide to adding information to a file in Nodejs depending on a condition

Looking for assistance on how to append an annotation (@Circuit(name = backendB)) to a file if the "createEvent" name exists and the annotation is not already present. I am unsure of the process, so any help on checking and appending using streams would ...

What strategies can be used to effectively structure CSS and JavaScript in a project for optimal organization?

In my NetBeans project, I currently have a large web project with CSS files included in the header. Some CSS codes are needed on all pages, while others are only necessary for specific pages. I am looking to optimize high-traffic pages by removing any ...

Creating a dynamic JSON object and retrieving the response in a JSP for data-driven documents

I am a beginner with the D3 API and I need to create a tree-like structure using a JSON file with hardcoded values. Additionally, I have a servlet that retrieves some values from a database which I want to dynamically convert into JSON in the servlet and s ...

Having difficulty retrieving the value of a variable obtained from the Google Distance Matrix function

Utilizing the Google distance matrix API to calculate the distance between two locations, I encountered an issue with global variable access. Despite changing the variable within a function, I found that I was unable to retrieve the updated value of the va ...

Having trouble creating a report with an HTML screenshot using Protractor

Need assistance with generating reports using a html screenshot in Protractor. I have followed all the necessary steps but encountered an error. Any help would be appreciated. Here is my conf.js: // Sample configuration file. var HtmlReporter = require(& ...

Modify the element within the Vuex store array upon modification of the component

Within my Vuex store, there exists an array of Notes, with each individual Note being represented by a <textarea>. I have a component called NoteArray that is responsible for displaying each Note: // NoteArray.vue export default { name: "NoteA ...

Animate the smooth transition of a CSS element when it is displayed as a block using JQuery for a

I have implemented the collapsible sections code from W3 School successfully on my website. Now, I am trying to achieve a specific functionality where the "Open Section 1 Button" should slide down with a margin-top of 10px only if the first section "Open S ...