Amazon
Amazon

Reputation: 476

How do I access my state object in store from module?

I need a data from my store object above in my module, but I cannot access it.

I have a store object

This store object has one or more modules it uses.

I was try it :index.js

import { createStore } from "vuex";

import moduleLayout from "./modules/moduleLayout.js"

export default createStore({
      state:{
           testData:'Hello World!'
      },
      modules: { moduleLayout }
})

and have a moduleLayout.js

export default {
  state:{
     size:100   
  },
  getters:{
        getSizeAndText:(state)=>{
             return {size:state.size,text:this.state.testData};
             
             //error here, because (this)undefined
             
             //how can i access on here testData
        }
  }
}

I cannot access testData data from my moduleLayout.js

Upvotes: 0

Views: 162

Answers (2)

Amazon
Amazon

Reputation: 476

No need to import index.js.

We can access it by expanding the parameter field.

on "index.js"

import moduleTest from "./modules/moduleTest";

export default{
    state:{
        size:100
    },
    modules:{
        moduleTest:moduleTest
    }
}

on "moduleTest.js"

export default{
    state:{
        testSize:20
    },
    getters: {
        getSumSize(thisState, getters, state) {
            return thisState.testSize+state.size;//this result 120
        },
        getSumSizeWithParam:(thisState, getters, state) =>(index)=>{
            return (thisState.testSize+state.size)*index;//this result 120*index
        }
    }
}

You definitely don't need to import index.js.

Upvotes: 1

rits
rits

Reputation: 1544

You are not adding the module to the store.

import { createStore } from "vuex";

import moduleLayout from "./modules/moduleLayout.js";

export default createStore({
  state: {
    testData: 'Hello World!'
  },
  modules: {
    layout: moduleLayout
  }
})

Import the store inside module to access the state thats not namespaced by module:

import store from '../index.js'; // whatever the path of where you create and export store

const state = {
    size: 100
}

const getters = {
    getSizeAndText(state) {
        return {
            size: state.size,
            text: store.state.testData
        }
    }
}

export default {
    state,
    getters
}

Upvotes: 0

Related Questions