闲云旅游项目开发-(第二篇:实现登录功能,使用vuex的store管理数据)
目錄
一 登錄注冊頁布局
二 登錄功能
1.思路
2.實現步驟
2.1 新建登錄表單組件
2.2 表單數據綁定及驗證
2.3 登錄接口
3.總結
?
三? 使用vuex/store管理數據
1.思路
2.實現步驟
2.1新建狀態文件
2.2實現登錄
2.3頂部組件,展示用戶信息
?
四 狀態持久化
1. 保存store到本地localStorage
?
2.思路
?
3.實現緩存信息到本地
3.1 安裝插件
3.2 引入
3.3 導入插件
?4.總結
?
本章涉及知識點:
- 使用vuex/store管理數據
- 登錄注冊邏輯
- Nuxt的本地存儲
一 登錄注冊頁布局
pages/user/login.vue 的布局代碼如下:
<template><div class="container"><!-- 主要內容 --><el-row type="flex" justify="center" align="middle" class="main"><div class="form-wrapper"><!-- 表單頭部tab --><el-row type="flex" justify="center" class="tabs"><span :class="{active: currentTab === index}" v-for="(item, index) in [`登錄`, `注冊`]":key="index" @click="handleChangeTab(index)">{{item}}</span></el-row><!-- 登錄功能組件 --><!-- <LoginForm v-if="currentTab == 0"/> --><!-- 注冊功能組件 --><!-- <RegisterForm v-if="currentTab == 1"/> --></div></el-row></div> </template><script> export default {data(){return {currentTab: 0}},methods: { //點擊tab欄根據index切換狀態handleChangeTab(index){this.currentTab = index;},} } </script><style scoped lang="less"> .container{background:url(http://157.122.54.189:9095/assets/images/th03.jfif) center 0;height: 700px;min-width:1000px;.main{width:1000px;height: 100%;margin:0 auto;position: relative;.form-wrapper{width:400px;margin:0 auto;background:#fff;box-shadow: 2px 2px 0 rgba(0,0,0,0.1);overflow:hidden;.tabs{span{display: block;width:50%;height: 50px;box-sizing: border-box;border-top:2px #eee solid;background:#eee;line-height: 48px;text-align: center;cursor: pointer;color:#666;&.active{color:orange;border-top-color: orange;background:#fff;font-weight: bold;}}}}} } </style>在預留的位置導入登錄組件和注冊組件
?
二 登錄功能
1.思路
- 在components/user 中新建 loginForm.vue 表單組件
- 使用 Element-ui 的表單組件
- 表單數據綁定
- 表單驗證
- 登錄接口
2.實現步驟
2.1 新建登錄表單組件
在components/user 中新建loginForm.vue組件,新增內容如下
<template><el-form :model="form" ref="form":rules="rules" class="form"><el-form-item class="form-item"><el-input placeholder="用戶名/手機"></el-input></el-form-item><el-form-item class="form-item"><el-input placeholder="密碼" type="password"></el-input></el-form-item><p class="form-text"><nuxt-link to="#">忘記密碼</nuxt-link></p><el-button class="submit"type="primary"@click="handleLoginSubmit">登錄</el-button></el-form></template><script> export default {data(){return {// 表單數據form: {},// 表單規則rules: {},}},methods: {// 提交登錄handleLoginSubmit(){console.log(this.form)}} } </script><style scoped lang="less">.form{padding:25px;}.form-item{margin-bottom:20px;}.form-text{font-size:12px;color:#409EFF;text-align: right;line-height: 1;}.submit{width:100%;margin-top:10px;} </style>?注意:新增了組件后在pages/user/login.vue 中導入,注冊即可使用。
導入位置:
<!-- 登錄功能組件 --><loginForm v-if="currentTab == 0" /><!-- 注冊功能組件 --><registerForm v-if="currentTab == 1" />2.2 表單數據綁定及驗證
修改data 的 form 數據,然后使用v-model綁定到對應的表單字段。
表單驗證:雙向數據綁定到form字段后,我們現在可以來提交表單了,但是提交之前還需要驗證下表單字段是否合法,比如不能為空。
編輯components/user/loginForm.vue
data() {return {// 表單數據form: {username: "13800138000",password: "123456"},// 表單規則rules: {username: [{ required: true, message: "請輸入用戶名", trriger: "blur" }],password: [{required: true,message: "請輸入密碼",trriger: "blur"},{min: 6,message: "密碼不能小于六位",trriger: "blur"}]}};使用el-form-item添加prop屬性
<el-form :model="form" ref="form" :rules="rules" class="form"><el-form-item class="form-item" prop="username"><el-input placeholder="用戶名/手機" v-model="form.username" @focus="clearRules('username')"></el-input></el-form-item><el-form-item class="form-item" prop="password"><el-inputplaceholder="密碼"type="password"v-model="form.password"@focus="clearRules('password')"></el-input></el-form-item>?現在可以嘗試在把input輸入框的值清空,會出現在rules中的定義的提示內容
2.3 登錄接口
接下來要調用登錄的接口進行登錄了,如果一切正常的話,我們可以看到后臺返回的用戶信息,如果登錄失敗,我們需要對統一對錯誤的返回進行處理,這個我們在最后再統一實現。
改components/user/loginForm.vue的提交登錄事件:
// 提交登錄async handleLoginSubmit() {// console.log(this.form);// 對整個表單進行驗證,如果輸入合法再進行發送請求this.$refs.form.validate(async v => {// console.log(v);if (v) {// console.log(this.form);let res = await userLogin(this.form);console.log(res);if (res.data.token) {this.$message.success("登錄成功");}} else {this.$message.error("請輸入合法內容");}});},?
3.總結
- 在components/user中新建loginForm.vue表單組件
- 使用Element-ui的表單組件綁定數據和驗證表單
- 調用登錄接口
?
三? 使用vuex/store管理數據
1.思路
使用vuex統一管理用戶登錄注冊行為和用戶信息
2.實現步驟
2.1新建狀態文件
在store文件夾新建user.js,并添加以下代碼
// 用戶管理 export const state = () => ({// 采用接口返回的數據結構userInfo: {token: "",user: {},}, }) export const mutations = {};export const actions = {};2.2實現登錄
登錄成功將數據放到 store/user.js 中統一管理
2.3頂部組件,展示用戶信息
在頭部組件展示store中保存的用戶數據
判斷token是否存在,存在則將用戶數據顯示出來:頭像路徑需要進行處理拼接基準路徑
<!-- 如果用戶存在則展示用戶信息,用戶數據來自store --><el-dropdown v-if="userInfo.token"><el-row type="flex" align="middle" class="el-dropdown-link"><nuxt-link to="#"><img :src="$axios.defaults.baseURL+ userInfo.user.defaultAvatar" />{{userInfo.user.nickname}}</nuxt-link><i class="el-icon-caret-bottom el-icon--right"></i></el-row><el-dropdown-menu slot="dropdown">?
四 狀態持久化
1. 保存store到本地localStorage
現在用戶已經保存到store了,但是還有一個問題,數據是保存在變量緩存中的,如果頁面一刷新,那么數據就會不見了,這樣是不合理的。
所以我們需要使用localStorage實現狀態持久化,
-
概念就是每當 vuex 數據發生變化, 就存放到 localStorage 里面去
-
每當頁面刷新的時候, localStorage 數據恢復到 vuex 里面
另外由于nuxtjs是運行在服務器的,不能直接在store中使用瀏覽器的localStorage方法,可以直接調用一個插件來實現以上的所有功能。
?
2.思路
找個插件幫忙vuex-persistedstate
?
3.實現緩存信息到本地
nuxtjs中store不能直接使用瀏覽器的lcoalStorage方法,
而且自己寫數據同步功能比較麻煩,
所以我們需要依賴一個插件vuex-persistedstate,該插件會把本地存儲的數據存儲到store。
插件地址:https://github.com/robinvdvleuten/vuex-persistedstate
3.1 安裝插件
npm install --save vuex-persistedstate
3.2 引入
需要創建一個 localStorage 自定義插件用來引入第三方包
以前我們引入第三方的插件時, 可以直接在 main.js 入口文件
的 new Vue 根實例創建之前, 添加代碼,
nuxt 的機制是自定義插件,存放在 plugins 文件夾, 然后用配置進行引入
在根目錄plugins中新建文件localStorage.js,加入以下代碼 :
import createPersistedState from 'vuex-persistedstate'export default ({store}) => {window.onNuxtReady(() => {createPersistedState({key: "store", // 讀取本地存儲的數據到store})(store)}) }3.3 導入插件
修改nuxt.config.js配置文件,在plugins配置項中新增一條數據 :
// 其他代碼...plugins: [// 其他代碼...// 這里的引入,如果是普通字符串,就在服務端馬上運行// 如果是要等到瀏覽器再運行的代碼,可以將配置改為對象,并且路徑作為src傳進去// 如果只在瀏覽器加載的代碼, 可以添加一個 屬性 ssr: false{ src: '@/plugins/localStorage', ssr: false } ],// 其他代碼...?如果只在瀏覽器加載的代碼, 可以添加一個 屬性 ssr: false
修改完后 重新啟動項目 npm run dev 就可以了
?
3.4 如果不使用插件也可以實現vuex 的持久化
在default.vue頁面進行store數據的管理:
mounted() {// 不使用插件 實現vuex持久化// 如果數據有變化,存放到localstorage// 如果頁面進入,將localStorage數據重新拿回來// this.$store.subscribe 可以訂閱 mutations// 任意一個 mutations觸發。都會在之后執行這個 subscribe 訂閱的回調this.$store.subscribe((mutation, state) => {localStorage.setItem("vuex", JSON.stringify(state));});// 如果頁面進入,將localStorage 數據重新拿回來// 本來所有數據的改變通過mutations// this.$store有一個函數例外,replaceState 傳入一個數據對象即可覆蓋原來的數據const savedState = localStorage.getItem("vuex");if (savedState) {this.$store.replaceState(JSON.parse(savedState));}}?
?
?
?4.總結
使用vuex-persistedstate 保存vuex到本地存儲
?
?
?
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的闲云旅游项目开发-(第二篇:实现登录功能,使用vuex的store管理数据)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 游戏配音制作软件有哪些好?看完你可能就知
- 下一篇: html5倒计时秒杀怎么做,vue 设