I am very new to state management and I got stuck in one position. Any help will be highly appreciated.
I have my store setup as:
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default function() {
const Store = new Vuex.Store({
modules: {},
state: {
isAdmin: false,
},
mutations: {
changeAuthStatus(state, authStatus) {
state.isAdmin = authStatus;
console.log(state.isAdmin) //output: true
}
},
actions: {
changeAuthStatus({ commit }, authStatus) {
commit("changeAuthStatus", authStatus);
}
}
});
return Store;
}
Before Entering to any route my route-guard will check if the user is 'Admin' or not and display the options in component accordingly.
My route guard is setup as:
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
import $store from "../store/index";
const store = $store();
let adminStatus = store.state.isAdmin;
const requireAuth = (to, from, next) => {
adminStatus = true;
store.dispatch("changeAuthStatus", authStatus);
}
if (adminStatus) {
next();
} else next({ name: "Home" });
};
const routes=[
{
{
path: "/",
name: "Home",
component: () => import("components/Home.vue")
},
path: "/add/",
name: "AddPost",
beforeEnter: requireAuth,
component: () => import("components/AddPost.vue")
}
]
export default function(){
const Router = new VueRouter({routes});
return Router;
}
And my 'AddPost.vue' component is setup as:
<template>
<div>
<div v-if="$store.state.isAdmin">
<h1>Welcome Admin </h1>
</div>
<div v-else> Welcome Guest </div>
</div>
</template>
<script>
export default {
created(){
console.log(this.$store.state.isAdmin); //output: false
}
}
</script>
On a positive response from server the state in vuex-store is mutating successfully to "isAdmin:true" but the component is not getting the updated status. I don't know what I am doing wrong. How can I solve this please?
question from:
https://stackoverflow.com/questions/65661677/vuex-get-state-after-mutation-in-components 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…