使用
在使用路由时我们常用到下面两个组件
- router-link
- router-view
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- 使用 router-link 组件来导航. -->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</div>
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App'
Vue.use(VueRouter)
// 1. 定义(路由)组件。
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
// 2. 定义路由
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
// 3. 创建 router 实例,然后传 `routes` 配置
const router = new VueRouter({
routes // (缩写)相当于 routes: routes
})
// 4. 创建和挂载根实例。
const app = new Vue({
el: '#app',
render(h) {
return h(App)
},
router
})
原理
1. 路由注册
2. VueRouter 对象
3. matcher
4. 路由切换
欢迎关注我的前端自检清单,我和你一起成长