总结demo:https://gitee.com/kkkklkm/vue-router
前端路由?
即前端维护一个路由规则
实现手段:
1,url的hash,js用hashChange监听。
2,利用html5的history模式。
vue-router的基本用法?
vue-cli安装带了vue-router的方式就不说了,下面记录下,手动加vue-router的过程
1,npm安装vue-router
2,main.js中增加
impoort VueRouter from 'vue-router'
Vue.use(VueRouter)
3,定义一个路由配置的数组
const Routers = [{path:xx,component:xxx},{path:yy,component:yyy}]
3,定义路由的其他配置项
const RouterConfig = {
mode:'history', //使用history模式
routes:Routers
}
5,定义路由实例,并放进Vue实例中
const router = new VueRouter(RouterConfig)
new Vue({})中增加一项:
router:router
6,package.json中'dev'里要增加 --history-api-fallback
小技巧(当地址填写成没有配置的地址时,让他跳回到主页)
Routers数组中,在最后增加一条
{path:'*',redirect:'/index'}
跳转
第一种
<router-link></router-link>
有tag属性(指定router-link渲染成什么标签)
replace属性(使用后,跳转不会留下历史记录)
active-class(会给当前元素设置一个名为router-link-active的class)
???????没太懂,以后来答疑
<router-link to="/about" tag="li" replace></router-link>
第二种
this.$router.push('/about') 这是正常的to跳转
this.$router.replace('xxx') 这是同上面的replace
this.$router.go(num) 这是走几步
高级用法
vue-router的实例提供了导航钩子
beforeEach 和 afterEach
demo
const router = new VueRouter(RouterConfig)
router.beforeEach((to,from,next)=>{
next()
})
to 表示即将要进入的目标的路由对象
from 表示当前导航即将离开的路由对象
next 调用这个方法后,才能进入下一个钩子
beforeEach的to中可以获取meta信息。
//解释下meta信息。这是可以写在路由配置中的一段信息。
//demo
const Routers = [
{
path:'/',
meta:{title:'首页'},
component:xxx
},
]