工具:
chorme浏览器安装Vue.js devtools方便调试
登录场景:
页面的导航处或其他地方有时会显示用户现在的登录状态,状态可分为:未登录,正在登录(loading),登录成功并显示用户名。 有些页面是不需要登录就可以让用户浏览的,但是有些页面必须登录才可以进入浏览。
实践:
场景1思考与实践
用vuex创建一个数据仓库 //src目录下新建一个store目录,创建index.js如下//创建数据仓库import Vuex from 'vuex';import vue from 'vue';import loginUser from 'loginUser.js'Vue.use(Vuex)const store = new Vuex.Store({ modules: { //modules 可以把不同的状态单独的放在一个对象里面 loginUser //是否正在登录中 }, strict: true, //只允许通过mutations改变状态}); 设置登录状态loading和当前登录用户user //创建一个loginUser.js,创建他的state/mutations/actions//需要维护的状态state: { loading: false, //登录状态 user: null, //当前登录的用户 },//计算属性getters: { status(state) { if (state.loading) { return 'loading' } else if (state.user) { return 'login' } else { return 'unLogin' } } }, //改变loading和user状态 mutations: { //设置loading setLoading(state, msg) { state.loading = msg }, //设置用户 setUser(state, msg) { state.user = msg } }, //actions中提交改变的状态 actions: { //登陆方法ctx相当于store async login(ctx, msg) { //登陆状态设置为true ctx.commit("setLoading", true) const result = await xxxapi.login(msg.loginId, msg.loginPassword) if (result) { //登录成功 ctx.commit('setUser', result) //登陆成功后登陆状态设置为false ctx.commit('setLoading', false) } //返回登陆是否成功 return result }, //判断是否已登录 async isLogin(ctx) { //正在登录中 ctx.commit('setLoading', true) //调接口是否登陆 const result = await xxxapi.isLogin(); ctx.commit('setUser', result); ctx.commit('setLoading', false) }, //注销 async logout(ctx) { ctx.commit('setLoading', false) await xxxapi.logout(); ctx.commit('setUser', null); ctx.commit('setLoading', false) } }, 页面使用: 在登录时,有一个登录按钮,按钮的状态我们就可以在Vuex的仓库中获取 <button :disabled="loading">{{ loading ? 'loading...' : '登录' }}</button>computed: {//在computed中封装一下loading,不用每次调用都写this.$store.state.loginUser这一堆 // loading() { // return this.$store.state.loginUser.loading; // } // 优化 //辅助函数 //import {mapState} from "vuex" ...mapState({ loading: (state) => state.loginUser.loading }) } 点击按钮的时候提交的时候分发action async handleSubmit() { const result = await this.$store.dispatch("loginUser/login", { loginId: this.loginId, loginPassword: this.loginPassword }); if (result) { // 登录成功 路由跳转 const path = this.$route.query.url || '/' this.$router.push(path) } }, 页面的导航中切换显示此时的登录状态[loading/login/unlogin] <!-- 显示页面登录状态--><span v-if="status === 'loading'">正在登录请稍等...</span><template v-else-if="status === 'login'"> <span>当前登录用户{{user.name}}</span> <span @click="handleLogout">退出</span></template><router-link to="/login" v-else> 登录</router-link> computed: {...mapGetters("loginUser", ["status"]),...mapState("loginUser", ["user"]),} 登出时 更改状态 async handleLogout(){ await this.$store.dispatch("loginUser/logout") //跳转到登陆页面 this.$route.push(/xxx)},每次页面刷新需要检测登录状态,在main.js中,也就是vue创建的时候就要判断。store.dispatch('loginUser/isLogin')
场景2思考与实践
参考了后台项目中的权限设置 总体设计: 刷新页面后,在Vuex仓库中先检测此时登录状态 下载地址: Vue实现控制商品数量组件封装及使用 typescript+react实现移动端和PC端简单拖拽效果 |