Vue Router
- 创建视图(路由相关组件)
- 注册路由插件(vue.use)
- 创建路由对象(配置规则)
- 创建路由对象
- 通过router-view占位
- router-link 创建链接
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
// 注册路由插件
Vue.use(VueRouter)
// 路由规则
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
},
{
path: '/detail/:id',
name: 'Detail',
// 开启 props,会把 URL 中的参数传递给组件
// 在组件中通过 props 来接收 URL 参数
props: true,
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "detail" */ '../views/Detail.vue')
},
{
path: '*',
name: '404',
// 懒加载, 可以提高程序的性能
component: () => import(/* webpackChunkName: "404" */ '../views/404.vue')
}
]
const router = new VueRouter({
mode: 'history',
routes
})
export default router
path: '/detail/:id',
如何获取id
<template>
<div>
<!-- 方式1: 通过当前路由规则,获取数据 -->
通过当前路由规则获取:{{ $route.params.id }}
<br>
<!-- 方式2:路由规则中开启 props 传参 -->
通过开启 props 获取:{{ id }}
</div>
</template>
<script>
export default {
name: 'Detail',
props: ['id'] // 父子组件传值
}
</script>
<style>
</style>
import Vue from 'vue'
import VueRouter from 'vue-router'
// 加载组件
import Layout from '@/components/Layout.vue'
import Index from '@/views/Index.vue'
import Login from '@/views/Login.vue'
Vue.use(VueRouter)
const routes = [
{
name: 'login',
path: '/login',
component: Login
},
// 嵌套路由
{
path: '/',
component: Layout,
children: [
{
name: 'index',
path: '',
component: Index
},
{
name: 'detail',
path: 'detail/:id',
props: true,
component: () => import('@/views/Detail.vue')
}
]
}
]
const router = new VueRouter({
routes
})
export default router
编程式导航
this.$router.push({ name: 'Home' })
this.$router.replace('/login')
this.$router.go(-1)
- $router.replace不会记录地址
- this.$router.go(负数)表示后退
- this.$router.go(-1) = this.$router.back
Hash模式
-
URL中#后面的内容作为路径地址
-
监听hashchange事件
-
根据当前路由地址找到对应组件重新渲染
History模式
-
通过History.pushState()方法改变地址栏
-
监听popstate事件
-
根据当前路由地址找到对应组件重新渲染
-
hash模式是是居于锚点,以及onhashchange事件
-
history模式是基于html5中的History API
-
history.pushState() IE10以后才支持
-
History.replaceState()
-