Vuex not working in child component

Refresh

December 2018

Views

3.4k time

1

The following simple code has been giving me a lot of headaches, since both some-component and the root instance log an error to the console instead of binding from the vuex object. What can i possibly be missing here?

var state = {
	counter: 0
};
var mutations = {};
var store = new Vuex.Store({state, mutations});

var someComponent = Vue.extend({
  template: '<div>{{counter}}</div>',
  //data: function(){return {counter: 0}},
  vuex: {
    getters: {
      counter: getCounter
    }
  }
});

new Vue({
  el: '#app',
  components: {
  	'some-component': someComponent
  },
  store: store,
  vuex: {
  	getters: {
  		counter: getCounter
  	}
  }
});


function getCounter(state) {
  return state.counter;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>vue-bug</title>
  </head>
  <body>
    <div id="app">
    	<span>{{counter}}</span>
    	<some-component></some-component>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.0-rc.1/vue.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.0.0-rc.1/vuex.js"></script>
  </body>
</html>

In my code, i'm calling Vue.use(Vuex), but in this fiddle i don't have to (it says that Vuex is already registered). Also, please notice that if you uncomment the line with the data, the component renders properly.

Any help is greatly appreciated.

1 answers

3

If you are using Vue/Vuex 2.0 you should take a look to this link. In vuex 2.0 you don't create a property vuex inside your components to set your getters and actions. Instead in your store.js file you define a getters object where you'll get the props from the state and then inject it to the store, like this:

const state = {
    counter: 0
}
const getters = {
    getCounter: state.counter
}

const actions = {}
const mutations = {}

export default new Vuex.Store({
    state,
    getters,
    actions,
    mutations,   
 })

In your components you can just define the getters using computed properties, like this:

import { mapGetter, mapActions } from 'vuex'

export default {
    template: '#some-template',
    computed: {
        yourFirstComputed() {},
        anotherOfYourComputed() {},
        ...mapGetters({
            getCounter: 'getCounter'
        })
    },
    methods: {
        yourMethod(){},
        ...mapActions({
             anyOfYourActions: 'anyOfYourActions'
        })
    }
}

Then you can call these props like you would with normal computed. I repeat, this apply for vuex 2 which i think you are using after reading the comments to the question.

I hope it helps!