vue-router安装和配置方式
vue-router安装
// 通过cli 安装
npm instll vue-router --save
vue-router配置
// 配置路由相关
import VueRouter from ‘Vue-router’
import Vue from ‘vue’
//通过懒加载的方式导入需要映射的组件
const Home = () => import('/Home')
const Profile = () => import('/Profile')
//vue中使用路由
Vue.use(VueRouter)
//创建路由对象
const routes=[
//redirect:'/home' 重定向设置,进入页面默认显示‘/home 内容’
{
path: '',
redirect:'/home'
},
{
path:'/home',
component: Home
},
{
path:'/profile',
component: Profile
}
],
//在VueRouter对象中使用routes,mode: 'history' 默认为hash不可返回
const router = new VueRouter({
routes,
mode: 'history'
})
//导出
export default router
将router挂载到App.vue中,在main.js 文件中添加
// 通过cli 安装
import router from './router'
new Vue({
el: '#app',
router,
render: h => h(App)
})
路由映射和呈现
在app.vue 中添’router-link’标签的to属性进行映射,用‘router-view’便签进行页面渲染
<div id=“app”>
//默认渲染为便签 其它格式需要添加tag属性 <router-link to="/home" tag="button">
<router-link to="/home">首页</router-link>
<router-link to="/profile">个人</router-link>
<router-view></router-view>
<div>
2.通过代码跳转
//监听事件下,执行如下,replace表示不可返回,用push 属性时表示可返回
this.$router.replace('/home')
this.$router.push('/profile')
路由嵌套使用
在映射关系中需要添加childrens属性,增加映射关系
{
path:'/home',
component: Home,
childerns[{
path:'/news',
component: new,
}
]
在渲染组件中需要添加完整的路径
<router-link to="/home/news">新闻</router-link>
<router-view></router-view>
路由的参数传递params&query
当路由跳转需要携带某些参数时,就需要动态路由,传递方式包括params和query
1.params类型
配置路由格式:/router/:id
传递方式:在path后面跟上对应的值
传递形成的路径:/router/123 /router/abc
取对应的参数值时:$route.params.id
//路由配置
{
path:'/home/:id',
component: Home
}
//渲染组件,id为动态需要传入的参数
<router-link :to="'/home'+id">
代码跳转时
this.$router.push(“‘/home'+id”)
)
2.query类型
配置路由格式:/router/ //正常配置
传递方式:对象中使用query的key作为传递方式
传递形成的路径:/touter?id=123,/touter?id=abc
取对应的参数值时:$route.query.id
//路由配置
{
path:'/home',
component: Home
}
//渲染组件,id为动态需要传入的参数
<router-link :to="/home"
query:{
id:123
}
>
//代码跳转时
this.$router.push(
path:'/home'
query:{
id:123
}
)
Vue-router 全局导航守位
导航守卫分为三类:全局守卫,路由独享守卫和组件守卫。含有有七个钩子函数包括三个参数 (to,from ,next),除了(后置钩子) afterEach,只有to,from
to:将要访问的路径
from:代表从哪个路径跳转而来
next:是一个函数表示放行
eg:
router.beforeEach((to,from,next)=>{
console.log("--------")
next()
})
keep-alive标签
在被 内嵌的视图会缓存,切换时,在路由组件切换时可以保持原来的状态 属性有include包含 ,exclude不包含
<keep alive exclued="Home">
<router-view> </router-view>
</keep alive >