【问题标题】:Vuex Get State After Mutation in componentsVuex 在组件中获取变异后的状态
【发布时间】:2021-04-16 02:09:21
【问题描述】:

我对状态管理很陌生,我被困在一个位置。任何帮助将不胜感激。

我的商店设置为:

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;
 }

在进入任何路由之前,我的路由守卫将检查用户是否为“管理员”,并相应地在组件中显示选项。

我的路由守卫设置为:

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;
}

我的“AddPost.vue”组件设置为:

<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>

在服务器的肯定响应中,vuex-store 中的状态已成功更改为“isAdmin:true”,但组件未获得更新状态。我不知道我做错了什么。请问这个怎么解决?

【问题讨论】:

    标签: javascript vue.js vuejs2 vuex vue-router


    【解决方案1】:

    导出存储对象而不是函数。否则,您在 main.js 中传递给 Vue 应用程序的商店(将其提供给组件)将与您在路由保护中使用的商店不同。

    export default new Vuex.Store({
      state: {},
      getters: {},
      mutations: {},
      actions: {},
      strict: true
    });
    

    【讨论】:

      【解决方案2】:

      您可以在 store 中定义一个 getter,它将返回 isAdmin 的状态,然后使用 getter 从 store 中获取组件中的值。

      【讨论】:

      • 做了,还是一样。
      • 如果$store.state.&lt;somevalue&gt; 有一个值,返回该值的getter 不会改变任何东西
      • 我可以在“console.log in commit (mutation)”中看到“true”。但组件总是“假”。
      猜你喜欢
      • 1970-01-01
      • 2019-04-30
      • 1970-01-01
      • 2020-11-16
      • 2019-11-30
      • 2019-03-20
      • 1970-01-01
      • 2018-01-20
      • 2020-06-23
      相关资源
      最近更新 更多