Vue Router
步骤
- 安装
npm i vue-router
- 配置router/index.js
import { createRouter, createWebHashHistory } from "vue-router"
import Xxx from "../view/color.vue"
const router = createRouter({
history: createWebHashHistory(),
routes:[
{
path: "/xxx",
components: Xxx
}
]
})
export default router
import router from "./router/index"
app.use(router)
- 呈现
<router-view/>
<RouterView>
- 切换
<router-link to="/">首页</router-link>
路由404
{
path: "/:pathMatch(.*)*",
component: () => import("../view/not-fount.vue")
},
两个路由 API
- $router 路由对象,可以用其提供的方法触发路由跳转
- $route 专门用于提取路由参数
路由懒加载与实现原理
const Home = ()=>import('../views/Home.vue')
const Login = ()=>import('../views/Login.vue')
路由传参
动态路由传参
- 设置形参 routes 配置的 path 后面
'/contact/:tel'
- 传递实参 router-link 的 to 属性中
to="/contact/xxx"
- 提取使用 在路由跳转的目标组件中
- template 区域
$route.params
- script 区域
this.$route.params
query 传参
- 传递实参 router-link 的 to 属性中
to="/login?name=xxx"
- 提取使用 在路由跳转的目标组件中
- template 区域
$route.query
- script 区域
this.$route.query
嵌套路由
步骤
- 新建子组件
- 配置子路由 为主路由添加 children
const routes = [
{
path: '/user/:id',
component: User,
children: [
{
path: 'profile',
component: UserProfile,
}
]
},
- 呈现子组件 需要在主组件内添加 router-view
- 触发跳转
编程式导航
this.$router.push(目标路由路径)
this.$router.push(`/prod/p2?id=123&name=xxx`)
this.$router.push({
path: `/prod/${target}`,
query: {
id: 123,
name: "xxx",
},
});
命名路由
{
path:'/p1',
name:'pp1',
component:P1
},
this.$router.push({
name:'pp1'
})
命名视图
<router-view/>
<router-view name="footer"/>
- 路由对应的组件使用 components 进行配置
{
path:'/login',
components:{
default:Login,
'footer':Footer
}
},
重定向和别名
{
path: "/",
redirect: "/color",
},
{
path: "/animal",
alias: "/",
}
Hash 模式与 History 模式
history 模式
- 项目上线的时候,如果后端不协助处理,项目访问会出现 404
http:
http:
hash 模式 【建议使用】
http: