/**
* 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>' }
// 路由
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">
<span @click="go">foo</span>
<router-view></router-view>
</div>
</template>
<script>
export default {
methods: {
go () {
// 编程式导航 替代 <router-link :to="...">
// 导航到 /foo/1
// this.$router.go(num) 前进 || 后退
this.$router.push({path: '/foo/1',})
this.$router.push({path: '/foo/1',})
}
}
}
</script>
/**
* Hello.vue
*/
<template>
<div class="hello">
<!-- $route.params.id : 获取路径参数 -->
路径参数 {{$route.params.id}}
<!-- 子组件 出口 -->
<router-view></router-view>
</div>
</template>