路由基础
安装Vue-router
一 、使用 Vue-cli 安装时,选中集成 Vue-router二 、使用 npm 安装
npm install vue-router -s
集成
创建vue-router对象
import Home from "./Home.vue"
;//将路径和组件一一对应,每一个配置项就是一条路由
const routes = [
{
path:"/",
name:"Home"
component:Home
},
{
},
{
}
]
// 新建vue对象,创建参数为对象类型,返回值:rrouter对象,路由管理对象
const router = new VueRouter({
mode:"history"//hash 前端路由和后端路由
//路由配置列表
routes
})
main.js
// 在挂载跟组件中,使用路由管理整个项目的组件
// 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由,
// 从而让整个应用都有路由功能
new Vue({
router,//使整个项目的组件都在vue-router的管理之下
render: h => h(App)
}).$mount('#app')
路由进阶
$router:路由管理对象
$route:每条路由的对象
push跳转
name+params
this.$router.history.push({
name:"路有名称",
params:{
"属性名称":{
}
}
})
path+query
this.$router.history.push({
path:"/路径",
query:{
"属性名称":"值"
}
})
this.$router.history.push({
name:"路有名称",
query:{
"属性名称":"值"
}
})
router-link
<router-link :to={
name:"路有名称",params:{
"属性名称":"属性值"}}></router-link>
动态路径参数
首先在路由配置文件中,修改路径,增加通配符 const routes = [
{
// 动态路径参数 以冒号开头
path:"/details/:参数名称"
}
]
<router-link :to="`/details/${参数的值}`"></router-lin>
获取路由传递数据
name+params
this.$route.query.属性名称
to={}
this.$route.query.属性名称
to+动态路径参数
this.$route.query.属性名称
路由元数据
可以在定义组件路由时,给每一个路由对象添加一些额外的属性
const routes = [
{
path: '/',
name: 'Home',
component: Home,
meta:{
isShowTabbar:true
}
},
{
path:"/category",
name:"Category",
component: Category,
meta:{
isShowTabbar:true
}
},
{
path:"/cart",
name:"Cart",
component: Cart,
meta:{
isShowTabbar:true
}
},
{
path:"/mine",
name:"Mine",
component: Mine,
meta:{
isShowTabbar:true
}
},
{
path:"/details",
name:"Details",
component:()=>import("../views/Details.vue"),
meta:{
isShowTabbar:false
}
}
]
可以通过组件的this.$route对象去获取
this.$route.meta.属性名称
嵌套路由
应用场景:
不常变化的业务场景使用,用于切换当前页面变化的部分
配置路由
哪个页面有嵌套路有,就在那个页面的路有对象中添加childred属性
const router = new VueRouter({
routes: [
{
path: '/user/:id', component: User,
children: [
{
// 当 /user/:id/profile 匹配成功,
// UserProfile 会被渲染在 User 的 <router-view> 中
path: 'profile',
component: UserProfile
},
{
// 当 /user/:id/posts 匹配成功
// UserPosts 会被渲染在 User 的 <router-view> 中
path: 'posts',
component: UserPosts
}
]
}
]
})
命名视图
假如整个项目大多数页面都有一个公共的组件,常规做法就是将这个公共组件引入到需要展示他的组件内,然后使用,频繁的引入并不是最好的处理方式,可以使用命名视图来进行处理
在组件中添加命名的router-view
<router-view name="header"></router-view>
在路由中配置
{
path:"/content",
name:"Content",
component:()=>import("../views/Content.vue"),
children:[
{
path:"/content",
components:{
header:Header,
// slider:Slider,
// content:Content,
// default:Slider
}
}
]
}