【问题标题】:Vue JS, show different menu if user authenticatedVue JS,如果用户经过身份验证,则显示不同的菜单
【发布时间】:2017-06-21 10:17:11
【问题描述】:

登录后,我在 store 和 localStorage 中设置变量 "authenticated" = true。

如果authenticated==true 并显示不同的菜单元素,我如何检查每个页面?

(我正在使用 ssr)

谢谢

【问题讨论】:

    标签: vue.js vuejs2 nuxt.js


    【解决方案1】:
    1. 在登录时设置 Vuex 状态 authenticated。
    2. 请务必清除当您注销用户或应用程序正在启动并且您正在检查例如如果 JWT 仍然有效。
    3. 在需要该状态的组件中设置计算变量。 computed() { authenticated () => { return this.$store.state.authenticated } }

    4. 在模板中使用 <v-if>。

    祝你好运!

    【讨论】:

      【解决方案2】:

      如果你不想使用 Vuex,

      1. 将初始状态{ authenticated: false }设置为vue-persistent-state。
      2. 使用 this.authenticated,就像在普通 Vue 应用中一样。

      例子:

      import persistentStorage from 'vue-persistent-storage';
      
      const initialState = {
        authenticated: false
      };
      Vue.use(persistentStorage, initialState);
      
      Vue.component('my-login', {
        methods: {
          login: function () {
            doLogin()  // call to auth API
              .then(() => { this.authenticated = true })
              .catch(() => { this.authenticated = false })
          }
        }
      })
      
      new Vue({
        el: '#app',
        created: function () {
          if (loginIsValid) {  // check auth validity upon app bootup
            this.authenticated = true
          } else {
            this.authenticated = false
          }
        }
      })
      

      现在authenticated 可作为所有组件和 Vue 实例中的数据使用。对 this.authenticated 的任何更改都将存储在 localStorage 中,您可以像在普通 Vue 应用中一样使用 this.authenticated。

      如果您想了解其工作原理,the code 非常简单。基本上是

      1. 添加 mixin 以使 initialState 在所有 Vue 实例中可用,并且
      2. 监视更改并存储它们。

      免责声明:我是vue-persistent-state的作者。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-14
        • 2018-03-11
        • 2021-03-23
        • 1970-01-01
        • 1970-01-01
        • 2018-10-10
        • 2015-03-12
        • 1970-01-01
        相关资源
        最近更新 更多