首页 > 其他 > 详细

Vue路由机制

时间:2020-04-23 17:39:13      阅读:65      评论:0      收藏:0      [点我收藏+]

Vue路由机制:通过组合组件来组成单页面应用(SPA)。将组件 (components) 映射到路由 (routes),然后告诉 Vue Router 在页面哪里渲染它们。

(1)组件(component)

(2)路由-组件映射表(routes)

(3)创建VueRouter,并传入映射关系(router)

(4)路由参数(router)注入Vue实例

 1 // 0. 如果使用模块化机制编程,导入Vue和VueRouter,要调用 Vue.use(VueRouter)
 2 
 3 // 1. 定义 (路由) 组件。
 4 // 可以从其他文件 import 进来
 5 const Foo = { template: ‘<div>foo</div>‘ }
 6 const Bar = { template: ‘<div>bar</div>‘ }
 7 
 8 // 2. 定义路由
 9 // 每个路由应该映射一个组件。 其中"component" 可以是
10 // 通过 Vue.extend() 创建的组件构造器,
11 // 或者,只是一个组件配置对象。
12 // 我们晚点再讨论嵌套路由。
13 const routes = [
14   { path: ‘/foo‘, component: Foo },
15   { path: ‘/bar‘, component: Bar }
16 ]
17 
18 // 3. 创建 router 实例,然后传 `routes` 配置
19 // 你还可以传别的配置参数, 不过先这么简单着吧。
20 const router = new VueRouter({
21   routes // (缩写) 相当于 routes: routes
22 })
23 
24 // 4. 创建和挂载根实例。
25 // 记得要通过 router 配置参数注入路由,
26 // 从而让整个应用都有路由功能
27 const app = new Vue({
28   router
29 }).$mount(‘#app‘) 

页面渲染(HTML)

 1 <div id="app">
 2   <h1>Hello App!</h1>
 3   <p>
 4     <!-- 使用 router-link 组件来导航. -->
 5     <!-- 通过传入 `to` 属性指定链接. -->
 6     <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
 7     <router-link to="/foo">Go to Foo</router-link>
 8     <router-link to="/bar">Go to Bar</router-link>
 9   </p>
10   <!-- 路由出口 -->
11   <!-- 路由匹配到的组件将渲染在这里 -->
12   <router-view></router-view>
13 </div>

 (4)this.$router ---  访问路由器;this.$route --- 访问当前路由

Vue路由机制

原文:https://www.cnblogs.com/psy-fei/p/12756077.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!