How to manage the logged in state of user in nativescript vue?

自闭症网瘾萝莉.ら 提交于 2019-12-25 01:44:06

问题


I was wondering how to handle login/logout of the user so I did this:

store.commit('load_state');
store.subscribe((mutations, state) => {
  ApplicationSettings.setString('store', JSON.stringify(state));
});

new Vue({
  store,
  render: h => h('frame', [h(store.state.is_logged_in ? App : Login)]),
  created() {
    this.$store.commit('setNav', this.$navigateTo);
    if (this.$store.state.is_logged_in) {
      this.$store.dispatch('init');
    }
  },
}).$start();

please note that loadstate initially loads the state from applicationsettings. But the problem with this solution is that this.$store is not available in the child components of Login.vue What would be the correct way to do this?

Please note that I'm not using vue-router here.


回答1:


I was struggling with this problem for two days until I finally found the solution.

My problem was because I was using $navigateTo without specifying the frame, I was navigating the whole component. I discovered that store was only bound to the first component that is passed to the render function in main.js

Here is how my main.js looked:

new Vue({
  store,
  render: h => h('frame', [h(store.state.is_logged_in ? Main : Login)]),
  created() {
    this.$store.commit('setNav', this.$navigateTo);
    if (this.$store.state.is_logged_in) {
      this.$store.dispatch('init');
    }
  },
}).$start();

I discovered that If is_logged_in was true this.$store, or mapActions etc only worked in Main and it's child components, otherwise it would only work in Login and it's child components. Then I was reading This and saw the following code in the store code of the example:

import Vue from 'nativescript-vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({...});
Vue.prototype.$store = store;
module.exports = store;

So I added the line Vue.prototype.$store = store; to my own store definition and finally my problem was solved. This really gave me such a hard time. Hope I can save somebody.



来源:https://stackoverflow.com/questions/57906540/how-to-manage-the-logged-in-state-of-user-in-nativescript-vue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!