溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vue怎么實(shí)現(xiàn)用戶訪問沒有登陸時自動跳轉(zhuǎn)登錄頁面

發(fā)布時間:2023-02-23 10:14:21 來源:億速云 閱讀:146 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了Vue怎么實(shí)現(xiàn)用戶訪問沒有登陸時自動跳轉(zhuǎn)登錄頁面的相關(guān)知識,內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇Vue怎么實(shí)現(xiàn)用戶訪問沒有登陸時自動跳轉(zhuǎn)登錄頁面文章都會有所收獲,下面我們一起來看看吧。

設(shè)計(jì)思路

  • 定義路由的時候配置屬性,這里使用needLogin標(biāo)記訪問頁面是否需要登錄

  • 設(shè)置路由守衛(wèi),每個頁面在跳轉(zhuǎn)之前都要經(jīng)過驗(yàn)證,校驗(yàn)用戶信息是否存在,不存在跳轉(zhuǎn)到登錄頁

  • 用戶登錄后將用戶信息存儲在localStorage

  • 退出登錄后,將用戶信息清空

 代碼實(shí)現(xiàn)

1、router文件夾的index.js文件中

  • 在router中每個地址在meta屬性中配置needLogin熟悉,判斷訪問頁面是否需要登錄

  • 404頁面放在最后,匹配所有鏈接,實(shí)現(xiàn)輸入不存在的地址時自動跳轉(zhuǎn)404頁面

import Vue from 'vue'
import Router from 'vue-router'
import LoginCard from "../components/LoginCard";
import Home from "../components/Home";
import ErrorPage from "../components/ErrorPage";

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'LoginCard',
      component: LoginCard,
      meta: {
        needLogin: false
      }
    },
    {
      path: '/loginCard',
      name: 'LoginCard',
      component: LoginCard,
      meta: {
        needLogin: false
      }
    },
    {
      path: '/home',
      name: 'Home',
      component: Home,
      meta: {
        needLogin: true
      }
    }, {
      path: '/*',
      name: 'ErrorPage',
      component: ErrorPage,
      meta:{
        needLogin: false
      }

    }
  ]
})

2、在main.js中定義一個路由前置守衛(wèi),每次跳轉(zhuǎn)頁面進(jìn)行判斷,沒有登陸自動挑戰(zhàn)登陸界面

import Vue from 'vue'
import App from './App'
import router from './router'
import VueRouter from "vue-router";
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import * as auth from './utils/auth'
import store from './store'
import Vuex from "vuex";

Vue.config.productionTip = false;
Vue.use(ElementUI);
Vue.use(VueRouter);
Vue.use(Vuex)


//這個方法需要放在new Vue之前,不然按F5刷新頁面不會調(diào)用這個方法
router.beforeEach(function (to, from, next) {
  console.log('是否需要登錄才能訪問')
  if (to.meta.needLogin) {
    if (auth.getAdminInfo()) {
      console.log(auth.getAdminInfo())
      console.log('有cookie信息')
      next();
    }else {
      console.log('無cookie信息')

      next({
        path:'/loginCard'
      });
    }
  }else{
    next();
  }
})

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

3、編寫一個存儲數(shù)據(jù)的工具,使用cookie存儲用戶登錄后的信息

import Cookies from 'js-cookie'
const adminInfo = "adminInfo"

//獲取用戶信息
export function getAdminInfo() {
  const admin = Cookies.get(adminInfo)
  if(admin){
    return JSON.parse(admin)
  }
  return ''
}
//存儲用戶信息
export function setAdminInfo(admin) {
  return Cookies.set(adminInfo, JSON.stringify(admin))
}
//移除用戶信息
export function removeAdminInfo() {

  return Cookies.remove(adminInfo)
}

4、寫一個登錄頁面,用戶登錄后就將數(shù)據(jù)存儲在cookie中

 <template>
  <div>
    <el-form ref="loginForm" :rules="formRules" :model="loginUser" label-width="80px" class="login-box">
      <h4 >歡迎登錄</h4>
      <el-form-item label="用戶名" prop="username">
        <el-input prefix-icon="el-icon-user" type="text" v-model="loginUser.username"  placeholder="請輸入用戶名" :maxlength="50" clearable></el-input>
      </el-form-item>
      <el-form-item label="密碼" prop="password">
        <el-input prefix-icon="el-icon-lock" type="password" v-model="loginUser.password"  placeholder="請輸入密碼" :maxlength="50" clearable>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">登陸</el-button>
        <el-button icon="" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import * as auth from '../utils/auth'
export default {
  name: 'LoginCard',
  data() {
    return {
      loginUser: {
        username: '',
        password: '',
      },
      formRules: {
        //制定表單輸入的規(guī)則
        username: [{required: true, message: '用戶名不能為空', trigger: 'blur'}],
        password: [{required: true, message: '密碼不能為空', trigger: 'blur'}]
      }
    }
  },
  methods: {

    onSubmit() {
      //判斷表單是否符合規(guī)則
      this.$refs['loginForm'].validate((valid) => {
          if (valid) {
            if (this.loginUser.username !== '123456' || this.loginUser.password !== '123456'){
              this.$message({
                message:'賬號或密碼錯誤',
                type: 'error',
              });
              return;
            }
            auth.setAdminInfo(this.loginUser);
            this.$router.push({path:'/home'});
          }
        }
      )
    },
    resetForm(){
      this.$refs['loginForm'].resetFields();
    },
  }
}
</script>
<style scoped>
.login-box {
  border: 1px solid #DCDFE6;
  width: 400px;
  margin: 180px auto;
  padding: 35px 35px 15px 35px;
  border-radius: 5px;
}
</style>

5、編寫一個退出頁面,用戶退出以后,將用戶信息從cookie中去除,跳轉(zhuǎn)到登陸頁面

 <template>
  <div>
    <h2>主頁面</h2>
    <el-button @click="logout">退出登錄</el-button>
  </div>
</template>
<script>
import * as auth from '../utils/auth'

export default {
  name : 'Home',
  data() {
    return {
    };
  },
  methods: {
    logout(){
      auth.removeAdminInfo();
      this.$router.push({path:'/loginCard'});
    }
  },
  mounted() {
  }
}
</script>

基本目錄結(jié)構(gòu)是這樣的

Vue怎么實(shí)現(xiàn)用戶訪問沒有登陸時自動跳轉(zhuǎn)登錄頁面

關(guān)于“Vue怎么實(shí)現(xiàn)用戶訪問沒有登陸時自動跳轉(zhuǎn)登錄頁面”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“Vue怎么實(shí)現(xiàn)用戶訪問沒有登陸時自動跳轉(zhuǎn)登錄頁面”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

vue
AI