简体   繁体   English

Vuex:安装钩中的吸气剂返回

[英]Vuex: Return getter in mounted hook

In my App.vue I am dispatching a Vuex action to retrieve a user from my API and also the role of the user like this: 在我的App.vue中,我调度了一个Vuex操作,以从我的API中检索user以及用户的role ,如下所示:

async mounted() {
    const userToken = localStorage.getItem('token');
    await this.getUserRole(userToken);
    await this.getUserImage(userToken);
  },

I wrote a getter that only returns me the current role that is saved in the user object like this getRole: state => state.user_role.role 我写了一个getter,它仅向我返回保存在用户对象中的当前角色,例如getRole: state => state.user_role.role

What I want to do is, that I want to dispatch an action regarding the user role in another view (Projects.vue): 我想做的是,我想在另一个视图(Projects.vue)中调度有关用户角色的操作:

async mounted() {
    console.log(this.$store.getters['user/getRole']);
    console.log(this.userRole);

    if (this.userRole === 'user') {
      // do things ...
    }
}
computed: {
    ...mapGetters('user', {
      user: 'getUser',
      userRole: 'getRole',
    })
}

The problem here is that at the first page load/refresh I get undefined back from my getter. 这里的问题是,在第一页加载/刷新时,我undefined从getter返回。 Only if I switch the route and come back, it returnes me in this case user instead of undefined . 仅当我切换路线并返回时,在这种情况下,它才返回user而不是undefined

I mean I could dispatch the user/getUserRole action again in my Project.vue but I guess that would be bad as I have multiple calls for the same store/action. 我的意思是我可以在Project.vue中再次分派user/getUserRole操作,但是我想那会很不好,因为我对同一个存储/操作有多个调用。

I also tried to work with $nextTick() in my mounted() but this did also not help. 我也试图与工作$nextTick()在我的mounted()但是这丝毫也没有帮助。

Since both routes need the same data, and the user can pretty much decide what route to access first -- you might want to initiate the API call in both routes, only adding a flag to it whether or not the specific call has already been initiated by other routes. 由于两条路由都需要相同的数据,并且用户几乎可以决定首先访问哪条路由-您可能希望在两条路由中都启动API调用,无论是否已启动特定的调用,都仅向其添加一个标志通过其他路线。

In your store states, you can define some sort of collection that holds boolean properties. 在商店状态中,您可以定义某种包含布尔属性的集合。

api_calls_ok: {
    user_data: false
}

Then you can define an action that does similar to this 然后,您可以定义一个与此相似的动作

const userToken = localStorage.getItem('token'); //side note: you can use localStorage.token instead
await this.getUserRole(userToken);
await this.getUserImage(userToken);

Maybe something like 也许像

getUserData({ commit, state }){
    if(!state.api_calls_ok.user_data){
        dispatch('getUserRole');
        dispatch('getUserImage');
        commit('flagApiCalls', 'user_data', true); //set the boolean to true
    }
}

In App.vue and Project.vue, you can just dispatch the getUserData during mount and not worry about calling the API twice or more. 在App.vue和Project.vue中,您可以在安装过程中分派getUserData ,而不必担心两次或多次调用API。 After dispatching, just access your getter. 分派后,只需访问您的吸气剂即可。

Watch the computed, and then execute the code once the user role is set, for example: 观察计算的结果,然后在设置了用户角色后执行代码,例如:

computed: {
    ...mapGetters('user', {
      user: 'getUser',
      userRole: 'getRole',
    })
},

watch: {
    userRole: {
        handler(role) {
             if (role) {
                 this.yourAction();
             }
        },
        immediate: true
    }
},

methods: {
    yourAction() {
        console.log('got role:', this.userRole);
    }
}

The immediate property is used within the watcher for userRole so that the handler will be called immediately when the component is loaded. userRole程序在userRole程序中使用immediate属性,以便在加载组件时立即调用处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM