Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call vuex store without mapState

Tags:

vue.js

vuex

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 }
})
like image 625
Jack Casas Avatar asked Sep 01 '25 10:09

Jack Casas


2 Answers

Actually I was looking for this way:

msg: this.$store.state.nombre

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

like image 123
Jack Casas Avatar answered Sep 04 '25 02:09

Jack Casas


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>
like image 39
Bennett Dams Avatar answered Sep 04 '25 01:09

Bennett Dams