首页 > 解决方案 > 如何在 nativescript vue 中管理用户的登录状态?

问题描述

我想知道如何处理用户的登录/注销,所以我这样做了:

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();

请注意 loadstate 最初从 applicationsettings 加载状态。但是这个解决方案的问题是 this.$store 在 Login.vue 的子组件中不可用,这样做的正确方法是什么?

请注意,我在这里没有使用 vue-router。

标签: vue.jsnativescriptnativescript-vue

解决方案


我在这个问题上苦苦挣扎了两天,直到我终于找到了解决方案。

我的问题是因为我在使用$navigateTo时没有指定框架,而是在导航整个组件。我发现 store 只绑定到传递给 main.js 中的渲染函数的第一个组件

这是我的 main.js 的样子:

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();

我发现 If is_logged_in 为 truethis.$storemapActionsetc 仅适用于Main它的子组件,否则它只会适用于Login它的子组件。然后我正在阅读This并在示例代码中看到以下代码store

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

所以我将这一行添加Vue.prototype.$store = store;到我自己的商店定义中,最后我的问题得到了解决。这真的让我很难受。希望我能拯救一个人。


推荐阅读