路由
Hash地址与组件之间的对应关系
前端路由的工作方式:
1.用户点击了页面是不同的路由链接
2.导致了url低智商的Hash值发生变化
3.前端路由监听到了Hash地址的变化
4.前端路由把当前Hash地址对应的组件渲染到浏览器中
底层原理:window.onhashchange()
<!-- 当安装和配置了vue-router后,就可以使用router-link
来替代普通的a链接 -->
<router-link to="/home">首页</router-link>
<router-link to="/movie">电影</router-link>
<router-link to="/about">关于</router-link>
<!-- <a href="#/home">首页</a> -->
<!-- <a href="#/movie">电影</a>
<a href="#/about">关于</a> -->
<hr />
<!-- vue-view组件占位符 -->
<router-view></router-view>
</div>
index,js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/components/Home.vue'
import Movie from '@/components/Movie.vue'
import About from '@/components/About.vue'
// 调用Vue.use()函数,把VueRouter安装为Vue插件
Vue.use(VueRouter)
const router=new VueRouter(
{
// 路由规则:
// route是一个数组,定义“Hash地址”与组件之间的对应关系
routes:[
{path:'/',redirect:'/home' },
{path:'/home',component:Home },
{ path:'/movie',component:Movie},
{path:'/about',component:About}
]
})
export default router
嵌套路由
通过children属性声明子路由规则
const router=new VueRouter(
{
// 路由规则:
// route是一个数组,定义“Hash地址”与组件之间的对应关系
// 默认子路由:如果children数组中,某个路由规则的path值为空字符串,
// 则这条路由规则名叫做默认子路由
routes:[
{path:'/',redirect:'/home' },
{path:'/home',component:Home },
{path:'/movie',component:Movie},
{path:'/about',
component:About,
redirect:'about/tab1',
children:[
{path:'tab1',component:Tab1},
{path:'tab2',component:Tab2}
]}
]
})
动态路由:把哈希地址中可变的部分定义为参数项,从而提高路由规则的复用性
在vue-router通过冒号:
// 在movie组件中,希望通过id的值来显示对应电影的详细信息
{path:'/movie/:id',component:Movie},
通过vue实例
this.$route.params.id来得到,id的值
通过main.js 通过props,允许通过自定义属性来获取到值
main.js
{path:'/movie/:id',component:Movie,props:true},
Movie.vue
<script>
export default {
name: 'Movie',
props:['id']
}
</script>
this.$route 路由的参数对象
this.$router 路由的导航对象
声名式导航:通过点击链接跳转的方式
编程式导航,调用api来跳转的
列如location.href
this.$router.push("hash地址")
跳转指定hash地址,并增加一条历史记录
this.$router.replace("hash地址")
跳转指定hash地址,并替换到刚才的历史记录,没有之前的历史记录
this.$router.go("数值n")
导航守卫
可以控制路由的访问权限
// 只要发生了路由跳转就会触发路由前置守卫函数
router.beforeEach((to,from,next)=>{
// console.log(to)
// to是将要访问的路由信息对象
// from是将要离开的路由的信息对象
// next是一个函数,调用next()表示放行,允许这次路由导航
next()
})