c.smits
c.smits

Reputation: 63

Get Vuex state data by passing a variable

I'm new on working with Vue and Vuex, and currently I'm trying to bind props to my component like this:

My HTML looks like this:

<div id="vuemodal">
  <modal :active="get('active')" :login="get('login')" :register="get('register')">
  </modal>
</div>

My Vue instance looks like this:

var modal = new Vue({
  el: '#vuemodal',
  store,
  data: {
    active: '',
    login: false,
    register: false,
  },
  methods: {
    get: function(item){
      var state = this.$store.state;
      return state.item;
   }
 }
})

My Vuex store looks like this:

const store = new Vuex.Store({
  state: {
    active: 'login',
    login: true,
    register: false
  }
})

In the "get" method, I would like to bind my "item" variable to my "state" variable. So the result will, for example, be this: this.$store.state.active (and it will return 'login'). When i console.log state.item, I get "undefined". What is the correct way to fix this, or should I try a complete different approach?

Upvotes: 1

Views: 5935

Answers (1)

Saurabh
Saurabh

Reputation: 73669

Here is the jsfiddle from your code, It is printing the store variables correctly. Make sure to use proper versions of Vue and Vuex.

const store = new Vuex.Store({
  state: {
    active: 'login',
    login: true,
    register: false
  }
})

var modal = new Vue({
  el: '#vuemodal',
  store,
  data: {
    active: '',
    login: false,
    register: false,
  },
  methods: {
    get: function(item){
      var state = this.$store.state;
      console.log("state is ", state[item])
      return state.item;
   }
 }
})

Upvotes: 2

Related Questions