Vue.js的路由(Vue Router)是什么
摘自官网:
Vue Router 是 Vue.js (opens new window)官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:
嵌套的路由/视图表
模块化的、基于组件的路由配置
路由参数、查询、通配符
基于 Vue.js 过渡系统的视图过渡效果
细粒度的导航控制
带有自动激活的 CSS class 的链接
HTML5 历史模式或 hash 模式,在 IE9 中自动降级
自定义的滚动条行为
那么什么是路由呢?
路由就是通过互联的网络把信息从源地址传送到目的地址的活动
路由提供了两种机制:路由和传送
路由是决定数据包从来源到目的地的路径
传送将输入端的数据转移到合适的输出端
而路由又分为两种:
1.后端路由
2.前端路由
Vue Router 则属于前端路由
Vue Router的使用:
使用 Vue + Vue Router 创建单页应用程序感觉很自然:使用 Vue.js,我们已经在用组件组合我们的应用程序。将 Vue Router 添加到组合中时,我们需要做的就是将我们的组件映射到路由,并让 Vue Router 知道在哪里渲染它们。这是一个基本示例:
#HTML
1 <script src="https://unpkg.com/vue/dist/vue.js"></script> 2 <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> 3 4 <div id="app"> 5 <h1>Hello App!</h1> 6 <p> 7 <!-- use router-link component for navigation. --> 8 <!-- specify the link by passing the `to` prop. --> 9 <!-- `<router-link>` will be rendered as an `<a>` tag by default --> 10 <router-link to="/foo">Go to Foo</router-link> 11 <router-link to="/bar">Go to Bar</router-link> 12 </p> 13 <!-- route outlet --> 14 <!-- component matched by the route will render here --> 15 <router-view></router-view> 16 </div>
#JavaScript
1 // 0. If using a module system (e.g. via vue-cli), import Vue and VueRouter 2 // and then call `Vue.use(VueRouter)`. 3 4 // 1. Define route components. 5 // These can be imported from other files 6 const Foo = { template: '<div>foo</div>' } 7 const Bar = { template: '<div>bar</div>' } 8 9 // 2. Define some routes 10 // Each route should map to a component. The "component" can 11 // either be an actual component constructor created via 12 // `Vue.extend()`, or just a component options object. 13 // We'll talk about nested routes later. 14 const routes = [ 15 { path: '/foo', component: Foo }, 16 { path: '/bar', component: Bar } 17 ] 18 19 // 3. Create the router instance and pass the `routes` option 20 // You can pass in additional options here, but let's 21 // keep it simple for now. 22 const router = new VueRouter({ 23 routes // short for `routes: routes` 24 }) 25 26 // 4. Create and mount the root instance. 27 // Make sure to inject the router with the router option to make the 28 // whole app router-aware. 29 const app = new Vue({ 30 router 31 }).$mount('#app')
// Now the app has started!
通过注入路由器,我们可以访问它this.$router以及this.$route任何组件内部的当前路由:
// Home.vue
1 export default { 2 computed: { 3 username() { 4 // We will see what `params` is shortly 5 return this.$route.params.username 6 } 7 }, 8 methods: { 9 goBack() { 10 window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/') 11 } 12 } 13 }
请注意,当 a 的目标路由匹配时,它<router-link>会自动获取.router-link-active该类。

浙公网安备 33010602011771号