VUE-路由配置及跳转方式
需求
在vue中,页面的他跳转和卡片切换一般会用到路由router,具体不多说,主要记录一下路由的配置和几种常用的跳转方式
路由配置重定向 index.js :
import Home from '../components/Home'
import Page2 from '../components/Page2'
import Chil1 from '../components/Chil1'
import Chil2 from '../components/Chil2'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/home',
name: 'Home', //可以不用name字段 但有时需要用到name匹配
component: Home
} ,
{
path: '/page2',
name: 'Page2',
component: Page2,
children:[ //页内切换卡片
{
path: '/chil1', // 带‘/’ 表示根路径
name: 'Chil1',
component: Chil1
},
{
path: 'chil2', // 不带‘/’ 表示访问路径为/page2/chil2
name: 'Chil2',
component: Chil2
}
]
},
{
path: '/', //匹配根路径 用于默认打开的页面
name: 'index',
redirect: '/home' //redirect重定向到Home组件
}
]
})
路由跳转的几种方式
一、使用标签路由 router-link
1、不传参
<router-link :to="{name:'Home'}">
<router-link :to="{path:'/home'}">
2、传参
<router-link :to="{name:'Home', params: {id:1}}">
<router-link :to="{path:'/home', params: {id:1}}">
// params传参数
// 路由配置 path: "/home/:id"
// 不配置path ,第一次可请求,刷新页面id会消失
// 配置path,刷新页面id会保留
// html 取参 $route.params.id
// script 取参 this.$route.params.id
<router-link :to="{name:'Home', query: {id:1}}">
// query传参数 (类似get,页面url后面会显示参数)
// 路由可不配置
// html 取参 $route.query.id
// script 取参 this.$route.query.id
二、编程式路由 this.$router.push()
1、不传参
this.$router.push('/home')
this.$router.push({name:'Home'})
this.$router.push({path:'/home'})
2、传参
this.$router.push({name:'home',params: {id:'1'}}) // 只能用 name
// params传参数
// 路由配置 path: "/home/:id"
// 不配置path ,第一次可请求,刷新页面id会消失
// 配置path,刷新页面id会保留
// html 取参 $route.params.id
// script 取参 this.$route.params.id
this.$router.push({name:'Home',query: {id:'1'}})
this.$router.push({path:'/home',query: {id:'1'}})
// query传参数 (类似get,页面url后面会显示参数)
// 路由可不配置
// html 取参 $route.query.id
// script 取参 this.$route.query.id
在axios中使用 this.$router.push() 时,如果使用function会取不到this而报错,而要使用箭头函数
如下:
onSubmit() {
axios.post('http://localhost:8022/user/login',qs.stringify(this.user))
.then((response)=>{ //正确; 使用function(response){}会报错。。。我也不知为啥。。
alert(response.data.msg);
if (response.data.url){
this.$router.push({path: '/home'})
}
})
.catch((error) => alert(error))
}
欢迎访问个人博客:http://www.itle.info/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)