javascript - 用于全局功能的 Vue 2 Mixins

标签 javascript vue.js vuejs2 mixins vue-mixin

我想实现一个简单的身份验证混合,用于应用程序和路由内的全局身份验证。 auth mixin 有一个 loggedIn 数据(True 或 False)以及两个用于登录和退出的函数。整个应用程序基于vue router webpack模板。问题是 loggedIn 状态不会被保存。因此,当我转到 Login.vue 并登录时,loggedIn 将设置为 true,但是当我再次转到 Login.vue 组件时,checkStatus 函数将记录 loggedIn再次为 false

我怎样才能

这是我的混音:

Auth.js

export default {
  data() {
    return {
      loggedIn: false
    }
  },
  methods: {
    logIn(user,password) {
      return new Promise((resolve, reject) => {
        console.log("Logging in ", user, password);
        this.loggedIn = true;
        resolve()
      })
    },
    logOut(){
      return new Promis ((resolve, reject) => {
        console.log("Logging out");
        this.loggedIn = false;
        resolve();
      })
    }
  }
};

main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import Utils from "./mixins/Utils"
import Auth from "./mixins/Auth"

// Load mixins
Vue.mixin(Auth);
Vue.mixin(Utils);

// This part redirects to login page when authentication is needed
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth) && this.loggedIn) {
    next({ path: '/login', query: { redirect: to.fullPath }});
  } else {
    next();
  }
});

登录.vue

<template>
  <div>
    <form class="form-signin">
      <h1 class="mb-3">Please sign in</h1>
      <label for="inputEmail" class="sr-only">Email address</label>
      <input type="email" id="inputEmail" v-model="email" class="form-control" placeholder="Email address" required autofocus>
      <label for="inputPassword" class="sr-only">Password</label>
      <input type="password" id="inputPassword" class="form-control" placeholder="Password" required v-model="password">
      <div class="checkbox mb-3">
        <label>
          <input type="checkbox" value="remember-me"> Remember me
        </label>
      </div>
      <button class="btn btn-lg btn-primary btn-block" type="submit" v-on:click="checkCredentials">Sign in</button>
    </form>
    <div class="mb-3" style="text-align: center">
      <label>
        <router-link to="/signup">Not registerd yet? Sign up!</router-link>
      </label>
    </div>
    <notifications position="bottom center" group="notifications" />
  </div>
</template>


<script>

  export default {
    name: 'Login',
    methods: {
      checkCredentials(event) {
        event.preventDefault();
        if (this.email.length <= 0 || !this.email) {
          this.notify("Enter email", "warn")
          return;
        }
        if (this.password.length <= 0 || !this.password) {
          this.notify("Enter password", "warn");
          return;
        }
        this.performLogin(this.email, this.password);
      },
      performLogin(mail, password) {
        let x = this;
        this.logIn(mail, password)
          .then(function (result) {
            x.notify("Logged in as " + mail, "success");
            if (x.loggedIn) {
              console.log("[LOG] redirecting");
              x.$router.push(x.$route.query.redirect || '/');
            }
          })
          .catch(function (error) {
            document.cookie = "Test";
            x.notify("Error loggin in (" + error + ")", "error");
          })
      },
      checkStatus() {
        this.$log.info("Checking status", this.loggedIn)
        if (this.loggedIn) {
          this.$router.push(this.$route.query.redirect || "/");
        }
      }
    },
    data() {
      return {
        email: "",
        password: ""
      }
    },
    created() {
      this.checkStatus()
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .form-signin {
    width: 100%;
    max-width: 330px;
    padding: 15px;
    margin: auto;
  }

  .form-signin .checkbox {
    font-weight: 400;
  }

  .form-signin .form-control {
    position: relative;
    box-sizing: border-box;
    height: auto;
    padding: 10px;
    font-size: 16px;
  }

  .form-signin .form-control:focus {
    z-index: 2;
  }

  .form-signin input[type="email"] {
    margin-bottom: -1px;
    border-bottom-right-radius: 0;
    border-bottom-left-radius: 0;
  }

  .form-signin input[type="password"] {
    margin-bottom: 10px;
    border-top-left-radius: 0;
    border-top-right-radius: 0;
  }
</style>

最佳答案

The problem is that the loggedIn state will not be saved.

确切地说,Mixin 并不用于管理状态,它们应该用于需要在组件中重用的函数/方法,为了维护状态,您需要一个状态管理系统,而 Vue 提供了一个,它是叫Vuex .

使用 Vuex,你可以定义一个初始状态,在你的情况下,无论用户是否登录,我建议你浏览 Vuex Docs一次

这是一个简短的示例,说明它将如何解决您的问题,

const store = new Vuex.Store({
 state: {
  loggedIn: false
 },
 mutations: {
  logInUser (state) {
  state.loggedIn = true
 }
}
})

/* Pass the store to your Vue App */
const app = new Vue({
  el: '#app',

  // this will inject the store instance to all child components.
  store,
  components: { App },
  ..........

现在,此状态将在您的整个组件中可用,并且不会更改,除非您从某处手动提交更改。

登录.vue

 this.$store.commit('logInUser', true)

someOtherComp.vue

console.log(this.$store.state.loggedIn) // true

关于javascript - 用于全局功能的 Vue 2 Mixins,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49984684/

相关文章:

javascript - Chrome 用户脚本中的正则表达式问题

javascript - 正则表达式小组赛

vue.js - Vue 3 v-select notwoking 中的更改事件

javascript - 如何组合两个组件 Vue.js

javascript - jQuery、bPopup - 如何将弹出窗口定位在右下角?

javascript - 如何编写具有多个:eq's in single expression?的jQuery选择器

javascript - Vue——​​全局导入

vue.js - 无法访问输入事件的 keyCode/key 事件

javascript - 无法增加/减少Vue中的数据属性值

java - 当数据更新时,VueJS DOM 不更新