Accessing state in a Vuex store module

Looking for guidance on how to access module store/state from another file. Here is a snippet of my code:

/store/index.js

import Vuex from 'vuex';
import categories from './modules/categories';

Vue.use(Vuex);
const store = new Vuex.Store({
  state: {
  },
  actions: {

  },
  mutations: {

  },
  getters: {

  },
  modules: {
    categories,
  },
});
export default store;

/store/modules/categories.js

const categories = {
  state: {
    categories: [
      {
        name: 'category1'
        path: 'path/to/there'
        subcategories: [
          {
            name: 'subcategory1'
            path: 'path/to/other/there'
            subsubcategory: [
              {
                name: 'subsubcategory1'
                path: 'path/to/other/there'
              }
              {
                name: 'subsubcategory1'
                path: 'path/to/other/there'
              }
            ]
          }
          {
            name: 'subcategory2'
            path: 'path/to/other/there'
          }
        ]
      }
      {
        name: 'category2'
        path: 'path/to/there'
        subcategories: [
          {
            name: 'subcategory2'
            path: 'path/to/other/there'
          }
          {
            name: 'subcategory3'
            path: 'path/to/other/there'
          }
        ]
      }
    ]
  },
  actions: {

  },
  mutations: {

  },
  getters: {

  },
}

In the /home.vue file, I am trying to access the modules' store/state to filter and display results. Here's part of the code:

<template>
  <div>
    <Headers></Headers>
    <div class="user row">
      <p>User Page</p>
      <p>I want to be able to access modules store/state here and use getters to filter some results from state.</p>
    </div>
    <Footers></Footers>
  </div>
</template>

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

export default {
  name: 'home',
  data() {
    return {
    };
  },
  methods: {
  },
  components: {
    Headers,
    Footers,
  },
  computed: {
    ...mapGetters([
      '',
    ]),
    ...mapState([
      'categories',
    ]),
  },
};
</script>

<style lang="scss" scoped>

</style>

Previous attempts at accessing and looping through categories were successful, but after correcting my store module structure, I'm facing challenges in accessing its state.

Thank you in advance, Cheers

Answer №1

Storing state data in modules.

I organize my store modules in this way.

This is the main index store located at stores/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import posts from '@/store/posts' // importing external store module
Vue.use(Vuex)
export default new Vuex.Store({
  modules: {
    posts
  },
  strict: true,
  plugins: [
    createPersistedState()
  ],
  state: {...... etc

Module for handling posts.

  // accessing the store console.log('module state', store.state.posts.data)
    export default {
      state: {
        data: 'dfsd'
      },
      getters: {
      },
      mutations: {
      },
      actions: {
      }
    }

Accessing data from a store module

Importing the store from '@/store/'

Retrieving data using store.state.posts.data

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

Removing the freshchat window across multiple pages in Vuejs

I am facing an issue with the fresh chat window on my website. I want to remove it from all pages except the home page. I have placed the script inside the mounted part of the home component, but once it loads, it never closes. It only disappears if I re ...

Having difficulties in loading the CSS file for my real-time chat application built with Express and Socket.io

Hi everyone, I've been struggling with an issue for the past couple of days where I can't seem to load my CSS for my Express app. If anyone has a solution, I would greatly appreciate the help. Below is my server.js code: const express = requir ...

What is the most effective way to access nested elements by index in JavaScript?

I am looking to design a user-friendly form that presents questions for users to navigate, revealing different answers/questions based on their responses. For example: var json = { "Did you restart the computer?": [ { ...

Having difficulty in successfully transmitting a dictionary via AJAX (POST) to Python (Django views) resulting in an empty dictionary every time

When I include this script in the head of the HTML : <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> and then use a button to call a function: <div> ...

The functionality of Bootstrap's Modal feature seems to be malfunctioning

I'm attempting to test the sample modals for my project, but even the codes from jfiddles are not working for me. When I click the button, it only gives me a dimmed window. I have also tried searching on Google for a solution, but to no avail. Below ...

Guide on creating a hover-based side menu

I am looking to enhance the sub-menus like PRODUCT 1, PRODUCT 2, etc. by adding side menus that appear when hovering over them. Can anyone assist with implementing this feature in the code below? Below is the current code snippet: CSS: @import url(http: ...

Navigating the world of updating problems with Express.js

Currently, I am working on a MEAN stack project and facing challenges with the routing for updating. Saving operations are functioning correctly. In my Angular controller, I have defined the following scope method in which staff represents the object subm ...

Angular6 HttpClient: Unable to Inject Headers in Get Request for Chrome and IE11

Under my Angular 6 application, I am attempting to make a GET request while injecting some custom Headers: Here is how my service is structured: @Injectable() export class MyService { constructor(public httpClient: HttpClient) { } getUserInfos(login): Ob ...

Translate a jQuery ajax request utilizing jQuery().serialize into plain JavaScript

Currently, I've been in the process of converting a jQuery script into vanilla JavaScript to completely eliminate the need for jQuery. The main functionality of the code includes: Upon clicking a button on the front end, an ajax request is sent, upda ...

SortTable - Refresh Dropdown Filter in Header After Adding Row to Table

My tablesorter table initially displays two entries in the "License" Filter. https://i.sstatic.net/4XODb.png If I dynamically add a row, the table now looks like this: https://i.sstatic.net/vMMYc.png I have attempted to update the table using the follow ...

Managing two variables in C# Controller and View

I am facing an issue with the two variables in my controller class. The first variable, currentUserId, is supposed to store the user currently logged into the website. The second variable, currentRoomId, should track the chat room the user is in. The probl ...

Retrieve a result from this promise

I have encountered a problem that my classmates at school cannot solve. I have a piece of code that is working fine and sending the table of objects potentials to the client side. However, I now realize that I also need another object called userData. I ...

Is it possible to dynamically alter a CSS property using styled components when an onClick event occurs?

Hey there, I'm pretty new to React and currently exploring styled components for the CSS styling of my components. One of the components I've created is a button called SummonButton: const SummonButton = styled.button` height: 50px; borde ...

One of the components in React failed to render even though data was successfully passed to both

I utilized React to create a submenu list. The parent component receives JSON data and passes it down to two child components. However, only one of the child components successfully displays the data while the other fails to do so. Both child components ...

Is it possible to access the ID of a collection_select and have a list of items appear whenever the selection is modified?

I am working on a form named _form.html.erb <%= simple_form_for(@exam) do |f| %> <%= f.error_notification %> <div class="field"> <%= f.label :Year %> <%= f.collection_select :year_id, Year.order(:name), :id, :name, ...

Warnings about NgZone timeouts are displayed in Chrome DevTools even though the timeouts are actually executing outside of the

Is it common to receive a warning in Chrome DevTools like this? [Violation] 'setTimeout' handler took 103ms zone.js:1894 even when all timeouts are executed outside of ngzone? I personally follow this approach: this.zone.runOutsideAngular(() = ...

The onClick function is called when I fail to click the button within a React form

I set up a form and I would like to have 2 ways to submit it: One by filling out the input field and pressing enter One by recording voice (using the react-speech-recognition library) However, after adding the second way, the input fi ...

Tips for removing "<li>" elements using JavaScript

My issue remains unresolved... I created a tree structure in MVC and added JavaScript code for expanding and collapsing the tree. However, after applying the code, my tree is not being displayed correctly. enter image description here In the image, you c ...

Vue.js Applications tend to encounter Expected Errors originating from JavaScript

I've been diving into learning Vue.js using Visual Studio 2017. Currently, my goal is to create applications with multiple buttons that trigger the display of a message upon being clicked. However, when I attempt to run this code, I encounter the foll ...

EcmaScript 6 bulk importing in JavaScript

In my ReactJS projects, I often find myself repeating the same imports in multiple classes: import MyClass from './some/path/foo.js'; import MyClass2 from './some/path/bar.js'; With a long list of imports, is there a way to consolidat ...