Vue 路由模式和404
路由模式有两种
- hash:路径带#符号,如:http://localhost/#/login
- history:路径不带#符号,如:http://localhost/login
修改路由配置,如下:
/** * 配置路由 */ import Vue from 'vue' import Router from 'vue-router' import Main from '../views/Main' import Login from '../views/Login' import UserList from '../views/user/List' import UserProfile from '../views/user/Profile' Vue.use(Router); export default new Router({ mode:'history', routes:[ { path:'/login', component:Login },{ path:'/main/:username', component:Main, props:true, children:[ //嵌套路由 { path:'/user/profile/:id', name:'UserProfile', component:UserProfile, props:true }, {path:'/user/list',component:UserList} ] }, { path:'/goHome', redirect:'/main' } ] });
路由钩子与异步请求
beforeRouteEnter:在进入路由前执行
beforeRouteLeave:在离开路由前执行
<template> <div> <h1>个人信息</h1> {{id}} </div> </template> <script> export default { props:['id'], name: "UserProfile", //过滤器 beforeRouteEnter:(to,from,next)=>{ console.log("进入路由之前"); next(); }, beforeRouteLeave:(to,from,next)=>{ console.log("进入路由之后"); next(); } } </script> <style scoped> </style>
参数说明
- to:路由将要跳转的路径信息
- from:路径跳转前的路径信息
- next:路由的控制参数
next() :跳转下一个页面
next('/path'):改变路由的跳转方向,使其跳到另一个路由
next(false):返回原来的页面
next((vm)=>{}):仅在beforRouteEnter中可用,vm是组件实例
在钩子函数中使用异步请求
1.安装Axios
cnpm install axios -s
2.在main.js引用axios 和 vue-axios
import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios,axios);
3.在static文件夹下创建测试数据文件夹 mock 并建立data.js文件
{ "name": "创客未来", "url": "https://www.baidu.com", "page": 1, "isNonProfit": true, "address": { "street": "hanguangmen", "city": "shanxixian", "country": "zhongguo" }, "links": [ { "name": "bilibili", "url": "https://www.baidu.com" }, { "name": "bilibili", "url": "https://www.baidu.com" } ] }
4.测试正常访问json数据
5.在个人信息组件Profile.vue中编写数据请求代码
<template> <div> <h1>个人信息</h1> {{id}} </div> </template> <script> export default { props:['id'], name: "UserProfile", //过滤器 beforeRouteEnter:(to,from,next)=>{ console.log("进入路由之前加载数据"); next(vm=>{ vm.getData();//进入路由之前执行getData方法; }); }, beforeRouteLeave:(to,from,next)=>{ console.log("进入路由之后"); next(); }, methods:{ getData:function () { this.axios({ method:'get', url:'http://localhost:8080/static/mock/data.json' }).then(function (response) { console.log(response) }) } } } </script> <style scoped> </style>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!