simplesin 2024-01-21 15:50 采纳率: 0%
浏览 19
已结题

前端页面进行this.$router.push('/');跳转不成功,一直卡在那里

img


代码如下:
这是index.vue

<template>
    <div class="login" >
        <div class="login-box">
            <div class="pt-20 pr-15 pl-15 pb-20">
                <input class="input mb-15" v-model="form.phone" placeholder="请输入手机号" type="number">
                <div class="box">
                    <input class="input" v-model="form.Code" placeholder="请输入短信验证码" type="number">
                    <div class="el-button" @click="send">{{ countDown }}</div>
                </div>
            </div>
            <!-- //<div class="btn" @click="sumbit">提交</div> -->
            <!-- //<el-button @click="sumbit"() => this.$router.push('/employee')">提交</el-button> -->
            <el-button @click.native ="okfine">登录
            
            </el-button>
           <!-- <el-button @click =()=>this.$router.push('/employee')>提交</el-button> -->
        </div>
    </div>
</template>

<script  >
    import {login,sendLoginMsgCode  } from '@/api/employee';
    export default {
        name: 'Login',
        data() {
            return {
                form: {
                    phone: '',
                    Code: '',
                    
                },
                countDown: "发送验证码", // 倒计时
                bVerification: false // 节流
            };
        },
        methods: {
      


         send() {
            if (!/^1[3-8]\d{9}$/.test(this.form.phone)) return this.$toast("请先输入正确的手机号");
            if (this.bVerification) return;
            this.bVerification = true;
            const { code } =  sendLoginMsgCode({
                phone: this.form.phone
            });
            if (code === 1) {
                this.$toast("发送验证码...");
                //  this.form.Code = '';
               
            }
            let countDown = 59;
            const auth_time = setInterval(() => {
                this.countDown = countDown--;
                if (this.countDown <= 0) {
                    this.bVerification = false;
                    this.countDown = "发送验证码";
                    clearInterval(auth_time);
                }
            }, 1000);
        },




         okfine() {
    if (!this.form.phone) {
        this.$message.error('请先输入手机号!');
        return;
    }
    if (!this.form.Code) {
        this.$message.error('请先输入验证码!');
        return;
    }
    login({
    phone: this.form.phone, 
    Code: this.form.Code
  }).then((res) => {
    // 检查后端返回结果
    if (res.data && res.data.code === 1) {
this.$nextTick(() => {
        this.$router.push('/employee');
      });
      


      this.$message.success('登陆成功');
      
    } else {
      this.$message.error('登录失败,请检查手机号和验证码是否正确');
    }
  }).catch((err) => {
    this.$message.error('请求出错了:' + err.message);
  });

        // const code =  login({
        //     phone: this.form.phone, 
        //     Code: this.form.Code
        // });alter("aaaaa")
        //     this.$message.success('登陆成功')
            
        // if (code == 1) {
            //this.$router.push('/');
        // } 
// const params = { phone: this.form.phone, Code: this.form.Code };
    // try {
    //     const code =  login({
    //         phone: this.form.phone, 
    //         Code: this.form.Code
    //     });
    //     if (code == 1) {
    //         this.$message.success('登陆成功')
    //         this.$router.push('/');
    //     } else {
    //         this.$message.error('登录失败,请检查手机号和验证码是否正确'+ err.message);
    //     }
    // } catch (err) {
    //     this.$message.error('请求出错了:' + err.message);
    // }
    // const params = { phone: this.form.phone, Code: this.form.Code };
    // try {
    //     const res = await login(params);
    //     if (res.data.code === 1) {
    //         this.$router.push('/employee/add');
    //     } else if (res.data.code === -1 || res.data.code === -2) {
    //         // 这里假设后端返回-1或-2代表验证码错误或无效
    //         this.$message.error('验证码错误或已过期,请重新获取并输入');
    //     } else {
    //         this.$message.error('登录失败,请检查手机号和验证码是否正确');
    //     }
    // } catch (err) {
    //     this.$message.error('请求出错了:' + err.message);
    // }
           
           
           
        //    login(params).then(res=>{
        //     if(res.data.code === 1){
        //         this.$router.push('/employee/add');
        //     }
        //    }).catch(err =>{
        //     this.$message.error('请求出错了:'+err.message)
        //    })


        //     const { Code, phone } = this.form
        //     if (!Code || !phone) return this.$toast("请输入手机号和验证码");
        //     let { code } = await login({
        //         phone,
        //         Code,
        //         isOffline: false
        //     });
        // this.$router.push('/employee/add');
    

            


            // if (code == 1) {
            //     //alert("来了")
            //     //this.$toast('登录成功');
            //     //this.$emit('sumbit', data.userInfo);
            //     this.$router.push('/employee/add')
            //     // this.$emit('update:dialog', false)
            // }
            console.log("跳转前")
        }

    }
}
</script>

<style lang='scss' scoped>
.login {
    height: 100vh;
    width: 100vw;
    background-color: rgba(0, 0, 0, .6);
    display: flex;
    justify-content: center;
    align-items: center;

    .main {
        width: 280px;
        height: 178px;
        background: #FFFFFF;
        border-radius: 5px;

        .input {
            border: 1px solid #EBEBEF;
            border-radius: 5px;
            height: 40px;
            padding-left: 10px;
        }

        .el-button {
            margin-left: 10px;
            border-radius: 5px;
            background: #5F93FD;
            color: #fff;
            width: 140px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .btn {
            height: 45px;
            color: #5F93FD;
            display: flex;
            justify-content: center;
            align-items: center;
            border-top: 1px solid #EBEBEF;
        }
    }
}
</style>


//以下是router.ts
import Vue from "vue";
import Router from "vue-router";
import Layout from "@/layout/index.vue";
// import {
//   getToken,
//   setToken,
//   removeToken,
//   getStoreId,
//   setStoreId,
//   removeStoreId,
//   setUserInfo,
//   getUserInfo,
//   removeUserInfo
// } from "@/utils/cookies";
// import store from "@/store";

Vue.use(Router);

const router = new Router({
  scrollBehavior: (to, from, savedPosition) => {
    if (savedPosition) {
      return savedPosition;
    }
    return { x: 0, y: 0 };
  },
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/login",
      component: () => import("@/views/login/index.vue"),
      meta: { title: "苍穹外卖", hidden: true, notNeedAuth: true }
    },
    {
      path: "/404",
      component: () => import("@/views/404.vue"),
      meta: { title: "苍穹外卖", hidden: true, notNeedAuth: true }
    },
    {
      path: "/",
      component: Layout,
      redirect: "/dashboard",
      children: [
        {
          path: "dashboard",
          component: () =>  import("@/views/dashboard/index.vue"),
          name: "Dashboard",
          meta: {
            title: "工作台",
            icon: "dashboard",
            affix: true
          }
        },
            {
          path: "/statistics",
          component: () => import("@/views/statistics/index.vue"),
          meta: {
            title: "数据统计",
            icon: "icon-statistics"
          }
        },
        {
          path: "order",
          component: () => import("@/views/orderDetails/index.vue"),
          meta: {
            title: "订单管理",
            icon: "icon-order"
          }
        },
        {
          path: "setmeal",
          component: () => import("@/views/setmeal/index.vue"),
          meta: {
            title: "套餐管理",
            icon: "icon-combo"
          }
        },
        {
          path: "dish",
          component: () => import("@/views/dish/index.vue"),
          meta: {
            title: "菜品管理",
            icon: "icon-dish"
          }
        },
        {
          path: "/dish/add",
          component: () => import("@/views/dish/addDishtype.vue"),
          meta: {
            title: "添加菜品",
            hidden: true
          }
        },
        
        {
          path: "category",
          component: () => import("@/views/category/index.vue"),
          meta: {
            title: "分类管理",
            icon: "icon-category"
          }
        },
        {
          path: "employee",
          component: () => import("@/views/employee/index.vue"),
          meta: {
            title: "员工管理",
            icon: "icon-employee"
          }
        },
        
        {
          path: "/employee/add",
          component: () => import("@/views/employee/addEmployee.vue"),
          meta: {
            title: "添加/修改员工",
            hidden: true
          }
        },
        
        {
          path: "/setmeal/add",
          component: () => import("@/views/setmeal/addSetmeal.vue"),
          meta: {
            title: "添加套餐",
            hidden: true
          }
        }
      ]
    },
    {
      path: "*",
      redirect: "/404",
      meta: { hidden: true }
    }
  ]
});

export default router;

//以下是main.ts
import Vue from 'vue'
import Router from 'vue-router'
import 'normalize.css'
import ElementUI from 'element-ui'
import SvgIcon from 'vue-svgicon'
import VueAreaLinkage from 'vue-area-linkage'
import moment from 'moment'
import '@/styles/element-variables.scss'
import '@/styles/index.scss'
import '@/styles/home.scss'
import 'vue-area-linkage/dist/index.css'
import VueRouter from 'vue-router'
// import App from './App.vue'
import routes from './router'
import * as echarts from 'echarts'
import '@/styles/newRJWMsystem.scss'
import '@/styles/icon/iconfont.css'
import App from '@/App.vue'
import store from '@/store'
import router from '@/router'
import '@/icons/components'
import '@/permission'
import { checkProcessEnv } from '@/utils/common'

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(VueAreaLinkage)
Vue.use(SvgIcon, {
  'tagName': 'svg-icon',
  'defaultWidth': '1em',
  'defaultHeight': '1em'
})

Vue.config.productionTip = false
Vue.prototype.moment = moment
Vue.prototype.$checkProcessEnv = checkProcessEnv
const routerPush = Router.prototype.push
Router.prototype.push = function push(location) {
 return routerPush.call(this, location).catch(error=> error)
}
Vue.prototype.$echarts = echarts
new Vue({
  router,
  store,
  'render': (h) => h(App)
}).$mount('#app')

//以下是package.josn
{
  "name": "project-sky-admin-vue-ts",
  "version": "0.1.0",
  "private": true,
  "author": "Chong Guo <armourcy@gmail.com>",
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "build:uat": "vue-cli-service build --mode production.uat",
    "lint": "vue-cli-service lint",
    "svg": "vsvg -s ./src/icons/svg -t ./src/icons/components --ext ts --es6",
    "test:e2e": "vue-cli-service test:e2e",
    "test:unit": "vue-cli-service test:unit"
  },
  "dependencies": {
    "@types/echarts": "^4.4.6",
    "@types/webpack": "^4.41.12",
    "area-data": "^5.0.6",
    "axios": "^0.19.0",
    "echarts": "^5.3.2",
    "element-ui": "^2.12.0",
    "js-cookie": "^2.2.1",
    "md5": "^2.3.0",
    "moment": "^2.24.0",
    "normalize.css": "^8.0.1",
    "nprogress": "^0.2.0",
    "path-to-regexp": "^3.0.0",
    "qcloudsms_js": "^0.1.1",
    "register-service-worker": "^1.6.2",
    "vue": "^2.6.10",
    "vue-area-linkage": "^5.1.0",
    "vue-class-component": "^7.1.0",
    "vue-property-decorator": "^8.2.2",
    "vue-router": "^3.1.2",
    "vue-svgicon": "^3.2.6",
    "vuex": "^3.1.1",
    "vuex-class": "^0.3.2",
    "vuex-module-decorators": "^0.10.1",
    "vuex-persistedstate": "^2.7.0"
  },
  "devDependencies": {
    "@types/jest": "^24.0.18",
    "@types/js-cookie": "^2.2.2",
    "@types/nprogress": "^0.2.0",
    "@types/webpack-env": "^1.14.0",
    "@typescript-eslint/eslint-plugin": "^4.0.0",
    "@vue/cli-plugin-babel": "^3.11.0",
    "@vue/cli-plugin-e2e-cypress": "^3.11.0",
    "@vue/cli-plugin-eslint": "^3.11.0",
    "@vue/cli-plugin-pwa": "^3.11.0",
    "@vue/cli-plugin-typescript": "^3.11.0",
    "@vue/cli-plugin-unit-jest": "^3.11.0",
    "@vue/cli-service": "^3.11.0",
    "@vue/eslint-config-standard": "^4.0.0",
    "@vue/eslint-config-typescript": "^4.0.0",
    "@vue/test-utils": "^1.0.0-beta.29",
    "babel-core": "^7.0.0-bridge.0",
    "babel-eslint": "^10.0.3",
    "eslint": "^5.16.0",
    "eslint-plugin-vue": "^5.2.3",
    "fibers": "^4.0.2",
    "jest": "^24.9.0",
    "sass": "^1.22.10",
    "sass-loader": "^7.3.1",
    "style-resources-loader": "^1.2.1",
    "ts-jest": "^24.0.2",
    "typescript": "3.6.2",
    "vue-cli-plugin-element": "^1.0.1",
    "vue-cli-plugin-style-resources-loader": "^0.1.3",
    "vue-eslint-parser": "^9.4.0",
    "vue-template-compiler": "^2.6.10",
    "webpack": "^4.39.3"
  }
}

后端无误,
测试结果
后端结果:

img

img

前端结果:

img

可是前端页面却一直不跳转

img

  • 写回答

14条回答 默认 最新

  • GISer Liu 2024-01-21 16:22
    关注

    该回答引用自GPT-4,由博主GIS_Liu编写:

    根据您的问题描述,您在使用 Vue.js 进行前端开发时遇到了路由跳转不成功的问题。我将根据您提供的信息,逐步分析问题并提供解决方案。

    问题分析:

    1. 路由设置:确保路由配置正确,且对应的组件或视图能够正确加载。
    2. 路由守卫:检查是否有全局或局部的路由守卫导致跳转被阻止。
    3. 网络请求处理:确认登录请求的处理和路由跳转的执行顺序是否正确。
    4. 路由跳转代码:检查this.$router.push('/')是否在正确的生命周期钩子或方法中被调用。
    5. 前端构建问题:如果是在生产环境下,确认构建后的资源是否正确加载。

    解决方案:

    1. 检查路由配置:查看router.ts确保路由配置没有问题。特别注意path: '/'对应的component: Layout是否正确导入并能正确渲染。

    2. 路由守卫检查:如果你使用了beforeEachbeforeEnter等路由守卫,请检查它们是否有阻止跳转的逻辑。

    3. 网络请求与跳转逻辑:在okfine方法中,确保登录请求(login)的响应处理逻辑是正确的,并且在调用this.$router.push('/')前没有其他异步操作导致的延迟。

    4. 路由跳转代码调用:确保this.$router.push('/')在Vue实例上下文中执行,并且没有被其他事件默认行为阻止。

    5. 检查Element UI Button事件绑定:在<el-button>标签中,应使用@click绑定事件处理器,而不是@click.native.prevent,除非有特别的需求需要阻止原生事件。

    6. 控制台调试:打开浏览器的开发者工具,查看控制台(Console)是否有任何错误信息,这可以提供为何路由跳转不成功的线索。

    7. Vue Router版本问题:有时候版本更新可能会引入一些不兼容的变化,确认你使用的Vue Router版本是否与你的Vue版本兼容。

    根据以上分析,我们可以先提供一个代码大纲:

    • 确保路由配置是正确的。
    • 检查是否有任何路由守卫(global or per-route)可能会影响跳转。
    • 确保okfine方法内部的逻辑没有问题,跳转逻辑是在登录成功后执行。

    接下来是具体代码:

    // 在okfine方法中,确保路由跳转的逻辑是这样的:
    okfine() {
      if (!this.form.phone) {
        this.$message.error('请先输入手机号!');
        return;
      }
      if (!this.form.Code) {
        this.$message.error('请先输入验证码!');
        return;
      }
      login({
        phone: this.form.phone,
        Code: this.form.Code
      }).then((res) => {
        // 检查后端返回结果
        if (res.data && res.data.code === 1) {
          // 使用nextTick确保DOM更新完成后执行跳转
          this.$nextTick(() => {
            this.$router.push('/dashboard');
          });
          this.$message.success('登录成功');
        } else {
          this.$message.error('登录失败,请检查手机号和验证码是否正确');
        }
      }).catch((err) => {
        this.$message.error('请求出错了:' + err.message);
      });
    }
    

    请注意,在this.$router.push('/');中,如果你的目的是跳转到根路径下的某个特定子路由,比如工作台dashboard,你可能需要使用this.$router.push('/dashboard');,而不是单独的'/'

    最后,请确

    如果该回答解决了您的问题,请采纳!如果没有,请详述问题所在!

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 1月24日
  • 修改了问题 1月21日
  • 修改了问题 1月21日
  • 创建了问题 1月21日

悬赏问题

  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作