hhhhhh9980 2024-04-26 14:51 采纳率: 50%
浏览 42
已结题

vue2登录调用后端接口如何实现

使用vue2+axios如何实现登录功能,用的是d2-admin开源框架,目前显示“登录成功”但无法跳转页面

//login/index.vue
<template>
  <div class="page-login">
    <div class="page-login--layer page-login--layer-area">
      <ul class="circles">
        <li v-for="n in 10" :key="n"></li>
      </ul>
    </div>
    <div
      class="page-login--layer page-login--layer-time"
      flex="main:center cross:center">
      {{time}}
    </div>
    <div class="page-login--layer">
      <div
        class="page-login--content"
        flex="dir:top main:justify cross:stretch box:justify">


        <div class="image">

          <img src="https://yayabucket.oss-cn-wulanchabu.aliyuncs.com/微信图片_20240426111346.png" style="width: 100%;height: 100%;">
        </div>


        <div
          class="page-login--content-main"
          flex="dir:top main:center cross:center">
          <!-- logo -->
          <!-- <img class="page-login--logo" src="./image/logo@2x.png"> -->
          <!-- form -->
          <div class="page-login--form"  style="margin-right: -100vh;margin-top: -50vh;">
            <el-card shadow="never"  style="margin-top:-400px;">
              <el-form
                ref="loginForm"
                label-position="top"
                :rules="rules"
                :model="formLogin"
                size="default">
                <el-form-item prop="username">
                  <el-input
                    type="text"
                    v-model="formLogin.username"
                    placeholder="用户名">
                    <i slot="prepend" class="fa fa-user-circle-o"></i>
                  </el-input>
                </el-form-item>
                <el-form-item prop="password">
                  <el-input
                    type="password"
                    v-model="formLogin.password"
                    placeholder="密码">
                    <i slot="prepend" class="fa fa-keyboard-o"></i>
                  </el-input>
                </el-form-item>
                <el-form-item prop="code">
                  <el-input
                    type="text"
                    v-model="formLogin.code"
                    placeholder="验证码">
                    <template slot="append">
                      <img class="login-code" src="./image/login-code.png">
                    </template>
                  </el-input>
                </el-form-item>
                <el-button
                  size="default"
                  @click="submit"
                  type="primary"
                  class="button-login">
                  登录
                </el-button>
                <el-button v-if="false" class="page-login--quick" size="default" type="info" @click="dialogVisible = true">
              快速选择用户(测试功能)
            </el-button>
              </el-form>
            </el-card>

            <!-- quick login -->


          </div>
        </div>

      </div>
    </div>
    <el-dialog
      title="快速选择用户"
      :visible.sync="dialogVisible"
      width="400px">
      <el-row :gutter="10" style="margin: -20px 0px -10px 0px;">
        <el-col v-for="(user, index) in users" :key="index" :span="8">
          <div class="page-login--quick-user" @click="handleUserBtnClick(user)">
            <d2-icon name="user-circle-o"/>
            <span>{{user.name}}</span>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { mapActions } from 'vuex'
import localeMixin from '@/locales/mixin.js'
import axios from 'axios'


export default {
  mixins: [
    localeMixin
  ],
  data () {
    return {
      timeInterval: null,
      time: dayjs().format('HH:mm:ss'),
      // 快速选择用户
      dialogVisible: false,
      users: [
        {
          name: 'Admin',
          username: 'admin',
          password: 'admin'
        },
        {
          name: 'Editor',
          username: 'editor',
          password: 'editor'
        },
        {
          name: 'User1',
          username: 'user1',
          password: 'user1'
        }
      ],
      // 表单
      formLogin: {
        username: 'admin',
        password: 'admin',
        code: 'v9am'
      },
      // 表单校验
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  mounted () {
    this.timeInterval = setInterval(() => {
      this.refreshTime()
    }, 1000)
  },
  beforeDestroy () {
    clearInterval(this.timeInterval)
  },
  methods: {
    ...mapActions('d2admin/account', [
      'login'
    ]),
    refreshTime () {
      this.time = dayjs().format('HH:mm:ss')
    },
    /**
     * @description 接收选择一个用户快速登录的事件
     * @param {Object} user 用户信息
     */
    handleUserBtnClick (user) {
      this.formLogin.username = user.username
      this.formLogin.password = user.password
      this.submit()
    },
    /**
     * @description 提交表单
     */

    async login(formLogin) {
      try {
        const url = this.$baseURL + 'sys/auth/login';
        const response = await axios.post(url, formLogin);
        // 假设登录成功时后端返回的状态码为200,并且token在response.data中
        if (response.status === 200) {
          // 登录成功,处理token,例如保存到localStorage或Vuex中
          // localStorage.setItem('token', response.data.token);
          this.$message.success('登录成功');
          console.log('gagaga')
          this.$router.replace(this.$route.query.redirect || '/')
          return response.data;
        } else {
          // 登录失败,抛出错误
          throw new Error('登录失败');
        }
      } catch (error) {
        // 捕获错误并提示用户
        this.$message.error('登录失败,请重试');
        throw error; // 可以选择是否重新抛出错误
      }
    },

    // submit () {
    //   this.$refs.loginForm.validate((valid) => {
    //     if (valid) {
    //       // 登录
    //       // 注意 这里的演示没有传验证码
    //       // 具体需要传递的数据请自行修改代码
    //       this.login({
    //         username: this.formLogin.username,
    //         password: this.formLogin.password
    //       })
    //         .then(() => {
    //           // 重定向对象不存在则返回顶层路径
    //           this.$router.replace(this.$route.query.redirect || '/')
    //         })
    //     } else {
    //       // 登录表单校验失败
    //       this.$message.error('表单校验失败,请检查')
    //     }
    //   })
    // }
    submit() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          try {
            // 调用登录方法
            await this.login({
              username: this.formLogin.username,
              password: this.formLogin.password,

            });

            // 登录成功后重定向
            this.$router.replace(this.$route.query.redirect || '/');
            console.log('成功')
          } catch (error) {
            // 捕获登录方法中的错误
            console.error(error);
          }
        } else {
          // 表单验证失败
          this.$message.error('表单校验失败,请检查');
        }
      });
    }
     // 提交登录信息
  }
  }

</script>

<style lang="scss">
.page-login {
  @extend %unable-select;
  $backgroundColor: rgb(255, 255, 255);
  // ---
  background-color: $backgroundColor;
  height: 100%;
  position: relative;
  // 层
  .page-login--layer {
    @extend %full;
    overflow: auto;
  }
  .page-login--layer-area {
    overflow: hidden;
  }
  // 时间
  .page-login--layer-time {
    font-size: 24em;
    font-weight: bold;
    color: rgba(0, 0, 0, 0.03);
    overflow: hidden;
  }
  // 登陆页面控件的容器
  .page-login--content {
    height: 100%;
    min-height: 500px;
  }
  // header
  .page-login--content-header {
    padding: 1em 0;
    .page-login--content-header-motto {
      margin: 0px;
      padding: 0px;
      color: $color-text-normal;
      text-align: center;
      font-size: 12px;
    }
  }
  // main
  .page-login--logo {
    width: 240px;
    // margin-bottom: 2em;
    // margin-top: -2em;
  }
  // 登录表单
  .page-login--form {
    width: 280px;
    // 卡片
    .el-card {
      margin-bottom: 15px;
    }
    // 登录按钮
    .button-login {
      width: 100%;
    }
    // 输入框左边的图表区域缩窄
    .el-input-group__prepend {
      padding: 0px 14px;
    }
    .login-code {
      height: 40px - 2px;
      display: block;
      margin: 0px -20px;
      border-top-right-radius: 2px;
      border-bottom-right-radius: 2px;
    }
    // 登陆选项
    .page-login--options {
      margin: 0px;
      padding: 0px;
      font-size: 14px;
      color: $color-primary;
      margin-bottom: 15px;
      font-weight: bold;
    }
    .page-login--quick {
      width: 100%;
    }
  }
  // 快速选择用户面板
  .page-login--quick-user {
    @extend %flex-center-col;
    padding: 10px 0px;
    border-radius: 4px;
    &:hover {
      background-color: $color-bg;
      i {
        color: $color-text-normal;
      }
      span {
        color: $color-text-normal;
      }
    }
    i {
      font-size: 36px;
      color: $color-text-sub;
    }
    span {
      font-size: 12px;
      margin-top: 10px;
      color: $color-text-sub;
    }
  }
  // footer
  .page-login--content-footer {
    padding: 1em 0;
    .page-login--content-footer-locales {
      padding: 0px;
      margin: 0px;
      margin-bottom: 15px;
      font-size: 12px;
      line-height: 12px;
      text-align: center;
      color: $color-text-normal;
      a {
        color: $color-text-normal;
        margin: 0 .5em;
        &:hover {
          color: $color-text-main;
        }
      }
    }
    .page-login--content-footer-copyright {
      padding: 0px;
      margin: 0px;
      margin-bottom: 10px;
      font-size: 12px;
      line-height: 12px;
      text-align: center;
      color: $color-text-normal;
      a {
        color: $color-text-normal;
      }
    }
    .page-login--content-footer-options {
      padding: 0px;
      margin: 0px;
      font-size: 12px;
      line-height: 12px;
      text-align: center;
      a {
        color: $color-text-normal;
        margin: 0 1em;
      }
    }
  }
  // 背景
  .circles {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    margin: 0px;
    padding: 0px;
    li {
      position: absolute;
      display: block;
      list-style: none;
      width: 20px;
      height: 20px;
      background: #FFF;
      animation: animate 25s linear infinite;
      bottom: -200px;
      @keyframes animate {
        0%{
          transform: translateY(0) rotate(0deg);
          opacity: 1;
          border-radius: 0;
        }
        100%{
          transform: translateY(-1000px) rotate(720deg);
          opacity: 0;
          border-radius: 50%;
        }
      }
      &:nth-child(1) {
        left: 15%;
        width: 80px;
        height: 80px;
        animation-delay: 0s;
      }
      &:nth-child(2) {
        left: 5%;
        width: 20px;
        height: 20px;
        animation-delay: 2s;
        animation-duration: 12s;
      }
      &:nth-child(3) {
        left: 70%;
        width: 20px;
        height: 20px;
        animation-delay: 4s;
      }
      &:nth-child(4) {
        left: 40%;
        width: 60px;
        height: 60px;
        animation-delay: 0s;
        animation-duration: 18s;
      }
      &:nth-child(5) {
        left: 65%;
        width: 20px;
        height: 20px;
        animation-delay: 0s;
      }
      &:nth-child(6) {
        left: 75%;
        width: 150px;
        height: 150px;
        animation-delay: 3s;
      }
      &:nth-child(7) {
        left: 35%;
        width: 200px;
        height: 200px;
        animation-delay: 7s;
      }
      &:nth-child(8) {
        left: 50%;
        width: 25px;
        height: 25px;
        animation-delay: 15s;
        animation-duration: 45s;
      }
      &:nth-child(9) {
        left: 20%;
        width: 15px;
        height: 15px;
        animation-delay: 2s;
        animation-duration: 35s;
      }
      &:nth-child(10) {
        left: 85%;
        width: 150px;
        height: 150px;
        animation-delay: 0s;
        animation-duration: 11s;
      }
    }
  }
}
</style>


```javascript
//store/modules/account.js
import { Message, MessageBox } from 'element-ui'
import util from '@/libs/util.js'
import router from '@/router'
import { SYS_USER_LOGIN } from '@/api/sys.user.js'

export default {
  namespaced: true,
  actions: {
    /**
     * @description 登录
     * @param {Object} context
     * @param {Object} payload username {String} 用户账号
     * @param {Object} payload password {String} 密码
     * @param {Object} payload route {Object} 登录成功后定向的路由对象 任何 vue-router 支持的格式
     */
    async login ({ dispatch }, {
      username = '',
      password = ''
    } = {}) {
      const res = await SYS_USER_LOGIN({ username, password })
      // 设置 cookie 一定要存 uuid 和 token 两个 cookie
      // 整个系统依赖这两个数据进行校验和存储
      // uuid 是用户身份唯一标识 用户注册的时候确定 并且不可改变 不可重复
      // token 代表用户当前登录状态 建议在网络请求中携带 token
      // 如有必要 token 需要定时更新,默认保存一天
      util.cookies.set('uuid', res.uuid)
      util.cookies.set('token', res.token)
      // 设置 vuex 用户信息
      await dispatch('d2admin/user/set', { name: res.name }, { root: true })
      // 用户登录后从持久化数据加载一系列的设置
      await dispatch('load')
    },
    /**
     * @description 注销用户并返回登录页面
     * @param {Object} context
     * @param {Object} payload confirm {Boolean} 是否需要确认
     */
    logout ({ commit, dispatch }, { confirm = false } = {}) {
      /**
       * @description 注销
       */
      async function logout () {
        // 删除cookie
        util.cookies.remove('token')
        // 清空 vuex 用户信息
        await dispatch('d2admin/user/set', {}, { root: true })
        util.cookies.remove('uuid')
        // 跳转路由
        router.push({ name: 'login' })
      }
      // 判断是否需要确认
      if (confirm) {
        commit('d2admin/gray/set', true, { root: true })
        MessageBox.confirm('确定要注销当前用户吗', '注销用户', { type: 'warning' })
          .then(() => {
            commit('d2admin/gray/set', false, { root: true })
            logout()
          })
          .catch(() => {
            commit('d2admin/gray/set', false, { root: true })
            Message({ message: '取消注销操作' })
          })
      } else {
        logout()
      }
    },
    /**
     * @description 用户登录后从持久化数据加载一系列的设置
     * @param {Object} context
     */
    async load ({ dispatch }) {
      // 加载用户名
      await dispatch('d2admin/user/load', null, { root: true })
      // 加载主题
      await dispatch('d2admin/theme/load', null, { root: true })
      // 加载页面过渡效果设置
      await dispatch('d2admin/transition/load', null, { root: true })
      // 持久化数据加载上次退出时的多页列表
      await dispatch('d2admin/page/openedLoad', null, { root: true })
      // 持久化数据加载侧边栏配置
      await dispatch('d2admin/menu/asideLoad', null, { root: true })
      // 持久化数据加载全局尺寸
      await dispatch('d2admin/size/load', null, { root: true })
      // 持久化数据加载颜色设置
      await dispatch('d2admin/color/load', null, { root: true })
    }
  }
}




```javascript

api/sys.user.js
import { find, assign } from 'lodash'
import faker from 'faker/locale/zh_CN'
import { requestForMock, mock } from '@/api/_service.js'
import * as tools from '@/api/_tools.js'

const users = [
  { username: 'admin', password: 'admin', uuid: 'admin-uuid', name: 'Admin' },
  { username: 'editor', password: 'editor', uuid: 'editor-uuid', name: 'Editor' },
  { username: 'user1', password: 'user1', uuid: 'user1-uuid', name: 'User1' }
]

/**
 * @description 登录
 * @param {Object} data 登录携带的信息
 */
export function SYS_USER_LOGIN (data = {}) {
  // 模拟数据
  mock
    .onAny('/login')
    .reply(config => {
      const user = find(users, tools.parse(config.data))
      return user
        ? tools.responseSuccess(assign({}, user, { token: faker.random.uuid() }))
        : tools.responseError({}, '账号或密码不正确')
    })
  // 接口请求
  return requestForMock({
    url: '/login',
    method: 'post',
    data
  })
}


  • 写回答

22条回答 默认 最新

  • 专家-赤兔[在线] 优质创作者: 编程框架技术领域 2024-04-26 14:54
    关注
    获得0.45元问题酬金

    引自免费微信小程序:皆我百晓生

    针对您遇到的问题,即在使用 Vue2、axios 和 d2-admin 开源框架时,虽然显示“登录成功”,但无法跳转页面,我将为您提供详细的解决方案。

    首先,您的登录功能实现已基本完成,但存在一些结构上的混乱和逻辑上的小问题。我已对您的代码进行了梳理和优化。以下是修改后的 login/index.vue 文件:

    <template>
      <!-- 省略模板部分 -->
    </template>
    
    <script>
    import dayjs from 'dayjs'
    import { mapActions } from 'vuex'
    import localeMixin from '@/locales/mixin.js'
    import axios from 'axios'
    
    export default {
      mixins: [localeMixin],
      data() {
        return {
          // 省略 data 部分
        }
      },
      // 省略 mounted, beforeDestroy 方法
      methods: {
        ...mapActions('d2admin/account', ['login']),
        async submit() {
          this.$refs.loginForm.validate(async (valid) => {
            if (valid) {
              try {
                // 调用登录方法
                await this.login({
                  username: this.formLogin.username,
                  password: this.formLogin.password,
                })
    
                // 登录成功后重定向
                this.$router.replace(this.$route.query.redirect || '/')
              } catch (error) {
                // 捕获登录方法中的错误
                console.error(error)
              }
            } else {
              // 表单验证失败
              this.$message.error('表单校验失败,请检查')
            }
          })
        },
      },
    }
    </script>
    
    <style lang="scss">
    /* 省略样式部分 */
    </style>
    

    主要更改如下:

    1. 删除了不必要的 async login(formLogin) 方法,因为它与您通过 Vuex mapActions 引入的 login 方法重名,导致实际调用的是 Vuex action 而非这里的局部方法。
    2. async login(formLogin) 中的逻辑移至 submit 方法内,直接调用 Vuex action this.login,并在登录成功后使用 this.$router.replace 进行页面跳转。

    接下来,请确保您的 store/modules/account.js 文件中的 login action 正确实现了登录逻辑,包括向后端发送登录请求、处理响应数据(如 token 存储、用户信息设置等)以及触发页面跳转。根据您提供的代码片段,这部分逻辑似乎已经完成。但为了确保无误,建议您检查以下几个关键点:

    1. 确认 SYS_USER_LOGIN API 请求地址和参数是否正确,以及后端接口是否正常工作。
    2. login action 的回调中,确保正确设置了 util.cookies.set('token', res.token)util.cookies.set('uuid', res.uuid),并将用户信息保存到 Vuex store(如 dispatch('d2admin/user/set', { name: res.name }, { root: true }))。
    3. 确保 load action 被成功触发,用于加载登录后的一系列设置。

    经过上述调整和检查,您的登录功能应该可以正常工作,即在输入正确的用户名和密码后,显示“登录成功”并成功跳转到指定页面。如果您在实施过程中遇到其他问题,请提供更详细的信息以便进一步排查。

    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 5月4日
  • 创建了问题 4月26日