vue-router
1、vue-router的理解:
vue的一个组件库,专门用来实现SPA应用
2、对SPA应用的理解:
1、单页Web应用
2、整个应用只有一个完整的页面
3、点击页面中的导航链接不会刷新页面,只会做页面的局部刷新
3、路由的理解:
1、一个路由就是一组映射关系(key - value)
2、key为路径,value可能是function (node根据路径做响应) 或component(用于展示页面内容)
3、工作过程:当浏览器的路径改变时,对应的组件就会显示
4、基本使用:
1、安装vue-router,命令:npm i vue-router
2、引用、应用插件:import VueRouter from 'vue-router'、 Vue.use( VueRouter )
3、编写router(路由器)配置项:
// 引入VueRouter
import VueRouter from 'vue-router'
// 引入 "路由" 组件
import About from '../components/About'
import Home from '../components/Home'
// 创建router实例对象,去管理一组一组的路由规则
const router = new VueRouter({
routes:[
{
path: '/about',
component: About
},
{
path: '/home',
component: Home
}
]
})
// 暴露router
export default router
4、实现切换(active-class可配置高亮样式)
<router-link active-class="active" to="/about"> About </router-link>
5、指定展示位置
<router-view></route-view>
5、几个注意点:
1、路由组件通常存放在 pages 文件夹, 一般组件通常存放在 components 文件夹。
2、通常切换,"隐藏"了的路由组件,默认是被销毁掉的,需要的时候再去挂载。
3、每个组件都有自己的 $route 属性,里面存储着自己的路由信息。
4、整个应用只有一个router,可以通过组件的 $router 属性获取到。
6、多级路由(嵌套路由)
1、配置路由规则,使用children配置项
routes:[
{
path: '/about',
component: About
},
{
path: '/home',
component: Home,
children: [ // 通过children配置子级路由
{
path: "news", // 此处一定不要写:/news
component: News
}
]
}
]
2、跳转(要写完整路径)
<router-link to="/home/news">News</router-link>
7、命名路由
1、作用:可以简化路由的跳转
2、如何使用:
1、给路由命名
children:[
{
name: "about", // 给路由命名
path: '/about',
component: About
},
]
2、简化跳转
// 简化前,需要写完整的路径
<router-link to="/home/about">About</router-link>
// 简化后,直接通过名字跳转
<router-link :to="{ name: 'about' }">About</router-link>
// 简化写法配合传递参数
<router-link
:to="{
path: "/home/detail",
query: {
id: 666,
title: "你好"
}
}"
>About</router-link>
7、路由传参:
1、路由的query参数
1、传递参数:
<!-- 跳转并携带query参数,to的字符串写法 -->
<router-link to=" /home/detail?id=666&title=你好 ">跳转</router-link>
<!-- 跳转并携带query参数,to的对象写法 -->
<router-link
:to="{
path: "/home/detail",
query: {
id: 666,
title: "你好"
}
}"
>跳转</router-link>
2、接受参数:
this.$route.query.id;
this.$route.query.title;
2、路由的params传参
1、配置路由
children:[
name: "detail",
path:"detail/:id/:title", //使用占位符声明接收params参数
component:Detail
]
2、传递参数:
<!-- 跳转并携带params参数,to的字符串写法 -->
<router-link to=" /home/detail/666/你好 ">跳转</router-link>
<!-- 跳转并携带params参数,to的对象写法 -->
<router-link
:to="{
path: "/home/detail",
params: {
id: 666,
title: "你好"
}
}"
>跳转</router-link>
3、接收参数
this.$route.params.id;
this.$route.params.title;

浙公网安备 33010602011771号