Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuex getters-properties Failure when using vue-router - they failed to be reactive

First, there is user.js, which is one of the modules for store.js

const state = {
  isLogin: false
}

const mutations = {
  login(state, userid){
    state.userid = userid;
  }
}

export default {
  state,
  mutations
}

Using Vue-router, I created an App Component, and imported store.js.
And then comes the Component login.vue. Following is part of the codes:

<script>    
export default {
  vuex: {
    actions: {
        login  // this action changes the state of
               // isLogin by dispatch `login` mutation
    }
  },

  methods: {
    btnClick(){
      // here calls the login action
    }
  }
} 
</script>

I noticed that the method btnClick can work in this component. It did changed the store.state.user.isLogin.

But here is another component a.vue listening the isLogin state:

<template>
...
  <a
    v-if="isLogin" 
    v-link="'#'">
    ...
  </a>
...
</template>

<script>
// import something
export default {
    vuex: {
      getters: {
        isLogin: ({ user }) => user.isLogin
      }
    }
}
</script>

When btnClick toggled in login.vue, the isLogin changed. But it seems that though the getter isLogin in a.vue was changed, thev-ifin <a> was not able to be reactive, for the <a> didn't appear.

I have tried to test if store is injected to child Components, and the result is it have passed. Also, I have tried to use computed instead of getters to listen isLogin, and it failed to be reactive either. when adding isLogin in watch attributes, it failed to watch.

And there is one thing that I am quite sure -- the Vue.use(Vuex) is not missed.

I was wondering whether it is the Vue-router which caused the problem.
And it seems that no one have asked questions about vuex with vue-router...

like image 308
Sam Chow Avatar asked Oct 31 '22 07:10

Sam Chow


1 Answers

I'm using vuex with vue-router and vue-resource (if you are authenticating users I assume that you are making HTTP requests) and it works just fine.

I think that your problem is your getter declaration. Getters receive the state inside the store object, and in your store declaration I don't see that the isLogin option is a property of user. I would change your getter to this.

vuex: {
  getters: {
    isLogin: state => state.isLogin
  }
}
like image 117
Yerko Palma Avatar answered Nov 09 '22 04:11

Yerko Palma