2
votes

So I'm experimenting with a new project created with vue cli, where I am using router and VueX

So in my HelloWorld.vue file, I've got this code in the script section:

import { mapState } from 'vuex'

export default {
  name: 'hello',
   computed: mapState({
    msg: 'nombre'
  }),

Is there a more direct way of calling values in the state?, like for example I would like to do

msg: store.nombre

My vuex store is defined in the root main.js like this:

//vuex
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    nombre: "POS vuex"
  }  
});

new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})
4

4 Answers

2
votes

Actually I was looking for this way:

msg: this.$store.state.nombre

(I was missing the ".state." part)

1
votes

As soon as you're using mapState as computed you can actually call these states with this in that component - in the template or script section:

Use the ... operator on your mapState and you're done:

Example:

Your store:

const store = new Vuex.Store({
  state: {
    nombre: "POS vuex",
    otherState: "abc",
    anotherState: "efg"
  }  
});

Your component:

<template>
  <div id="test">
    {{ nombre }}
    {{ otherState }}
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'hello',
   methods: {
     logState() {
       console.log(this.anotherState);
     }
   },
   computed: {
     ...mapState(["nombre", "otherState", "anotherState"]),
   }
}
</script>
0
votes

In addition to the the mapState helper

computed: {
  ...mapState('moduleOne', ['keyOne', 'keyTwo'])
}

which lets you access the values via this.keyOne and this.keyTwo inside your component.

You can also add your store to the root vue instance and access your state inside your components via the global this.$store directive.

this.$store.module.keyOne
this.$store.module.keyTwo

Additionally if you need to access your store from outside your components you can also export the store and import it directly from non-component code.

If you export your store:

import Vue from 'vue'
import Vuex from 'vuex'
import moduleTwo from './modules/moduleOne'
import moduleOne from './modules/moduleTwo'

Vue.use(Vuex)

const store = new Vuex.Store({
  strict: true,
  modules: {
    moduleOne,
    moduleTwo
  }
})

export default store

You can import it anywhere you need to access state, getters, actions, and mutations.

import store from '@/store'

console.log(store.state.moduleOne.keyone)
store.dispatch('moduleOne/actionOne', { keyOne: valOne })
store.getters['moduleOne/getterOne']
store.commit('moduleOne/mutationOne', data)
-1
votes

Call you'r state in created method of vuex.

THanks