起步
用 Vue.js + Vue Router 创建单页面应用, 通过 Vue 组合组件来组成应用程序, 将 Vue Router 添加进来. 将组件映射到路由, 然后告诉 Vue Router 在哪里渲染他它们
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <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>Hi Ginger</h1> <p> <router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> </p> </div>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
const Foo = { template: '<div>Foo</div>' } const Bar = { template: '<div>Bar</div>' }
const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ]
const router = new VueRouter({ routes })
const app = new Vue({ router }).$mount('#app')
|
通过注入路由器, 我们可以在任何组件内通过 this.$router 访问路由器, 也可以通过 this.$route 访问当前路由
1 2 3 4 5 6 7 8 9 10 11 12 13
| export default { computed: { username() { return this.$route.params.username } }, methods: { goBack() { window.history.length > 1 ? this.router.go(-1) : this.$router.push('/') } } }
|
当 <router-link> 对应的路由匹配成功,将自动设置 class 属性值 .router-link-active。