你不知道的前端开发小技巧1

292 阅读1分钟

前言:最近在登录某网时,发现登录后进入的页面是我上次退出的页面,好神奇!!!,就在思考是怎么实现的,碰巧最近在做项目也遇到了同样的需求,下面是实现过程:

功能需求

退出登录,再次登录回到退出前的页面

http://localhost:8080/#/settings 这个地址退出

image.png

再次登录回到 http://localhost:8080/#/settings 这个地址 image.png

功能分析与思路

分析:

  1. 登录成功,进入指定的页面(注:不要每次登录进入首页) image.png
  2. 退出登录,跳到登录页,需要携带目标页面的地址给登录页

思路
在访问登录页时,在地址栏补充一个查询字符串来指定登录成功之后要求去的页面,例如:

// 访问登录页,告诉登录后要去/settings这个页面
http://localhost:8080/#/login?return_url=%2Fsettings

退出登录时回传当前路径给login

实现代码

退出登录时

    logout() {
      // 弹层询问,是否退出
      this.$confirm('你确定要离开吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await this.$store.dispatch('user/delLogin')
        // this.$route.fullPath:路径+查询参数的信息
        // encodeURIComponent: 是js的内置API,用来对url进行编码
        // return_url 这个名字是自己定的,它要和login/index.vue中跳转代码保持一致
        this.$router.push('/login?return_url=' + encodeURIComponent(this.$route.fullPath))
      }).catch(() => {
        // 用户取消退出
      })
    }

登录时

  async  handleLogin() {
      try {
        await this.$store.dispatch('user/getlogin', this.loginForm)
        const return_url = this.$route.query.return_url || '/'
        // 如果this.$route.query.return_url没有路径就跳转到首页
        // 登录成功,路由跳转
        this.$router.push(return_url)
      } catch (error) {
        console.log(error)
      }
    }

感谢阅读^_^