/**
* main.js
*/
import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'
import hello from './components/Hello.vue'
Vue.use(VueRouter)
// 定义路由组件
const Foo = hello
const Bar = { template: '<div>bar</div>' }
// 动态路由
// path : 路由路径
// :id 匹配任意参数
// :name 匹配任意参数
// component : 该映射对应的组件
const routes = [
{ path: '/foo/:id', component: Foo },
{ path: '/bar/:name', component: Bar }
]
/* eslint-disable no-new */
// 创建router实例 传入routers参数
const router = new VueRouter({
routes
})
new Vue({
el: '#app',
template: '<App/>',
router,
components: { App }
})
/**
* App.vue
*/
<template>
<div id="app">
<p>
<!--
使用 router-link 组件来导航 通过传入 to 属性指定链接
<router-link> 默认会被渲染成一个 <a> 标签
-->
<router-link to="/foo/1">Go to Foo</router-link>
<router-link to="/bar/2">Go to Bar</router-link>
</p>
<!--
路由出口
路由匹配到的组件将渲染在这里
-->
<router-view></router-view>
</div>
</template>
/**
* Hello.vue
*/
<template>
<div class="hello">
<!-- $route.params.id : 获取路径参数 -->
路径参数 {{$route.params.id}}
</div>
</template>