本案例代码将使用 ES2015 来编写。
Vue.js + Vue Router 创建单页应用,是非常简单的。使用Vue.js ,我们已经可以通过组合组件来组成应用程序,当你要把 Vue Router 添加进来。我们需要做的是,将组件 (components)映射到路由 (routes),然后告诉 Vue Router 在哪里渲染它们。 下面是个基本例子:
HTML
<script src="https://unpkg.com/vue/dist/vue.js"> </script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<h1> hello app!</h1>
<!-- 使用router-link 组件来导航 -->
<!-- 通过传入 'to' 属性指定链接 -->
<!-- <router-link> 默认会被渲染成一个 <a> 标签 -->
<p>
<router-link to="/foo"> Go to Foo </router-link>
<router-link to="/bar"> Go to Bar </router-link>
</p>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里-->
<router-view></router-view>
JavaScript
// 0. 如果使用模块化机制变成,导入Vue和VurRouter,要调用 Vue.use(VueRouter)
// 1. 定义 (路由) 组件
// 可以从其他文件 import 进来
const Foo = {template:'<div> Foo </div>'}
cosnt Bar = {template:'<div> Bar </div>'}
// 2. 定义路由
// 每个路由应该映射一个组件。。其中component 可以是
// 通过Vue.extend() 创建的组件构造器
// 或者,只是一个组件配置对象。
// 我们晚点再讨论嵌套路由
const routes = [
{path:'/',component:FOO}, // 默认
{path:'/foo',component:Foo},
{path:'/bar',component:Bar}
]
// 3. 创建 router 实例,然后传 routes 配置
// 还有传别的配置参数,不过先这么简单着吧。
const router = new VueRouter({
routes:routes // 也可缩写 routes
})
// 4. 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由
// 从而让真个应用都有路由功能
const app = new Vue({
router
}).$mount('#app')
通过注入路由器,我们可以在任何组件内通过 this.$router 访问路由器,也可以通过 this.$route 访问当前路由:
// Home.vue
export default{
computed:{
username(){
// 我们很块就会看到 ‘params’ 是什么
return this.$route.params.username
}
},
methods:{
goBack(){
window.history.length >1?this.$router.go(-1):this.$router.push('/')
}
}
}
该文档通篇使用 router 实例。
留意以下 this.$router 和 router 使用起来完全一样。
我们使用 this.$router 的原因是我们并不想在每个独立需要封装路由的组件中都导入路由。
要注意, 当