// 定义路由规则 const routes = [ { name:'首页', path: '/', component: function (resolve) { require.async(['js/modules/Index.js'], resolve); } }, { name:'详情页产品列表页', path: '/detail/:params1/:params2', component: function (resolve) { require.async(['js/modules/detail.js'], resolve); } }, { name:'产品列表页', path: '/product', component: function (resolve) { require.async(['js/modules/product.js'], resolve); } } ] // 创建一个路由器实例 var router = new VueRouter({ routes }); //路由器会创建一个 App 实例,并且挂载到选择符 #app 匹配的元素上。 const app = new Vue({ router }).$mount('#app')
[聚合文章] vue-router源码学习(一)
页面代码
页面使用方式
由于是学习,就不是webpack进行项目工程化。这里实用seajs去获取相应的组件信息。
从实用角度分析: vue-router 插件给我们提供了两个组件:
<router-view> 与 <router-link>,其中<router-view>是必需组件。
(二)源码目录结构
components: <router-view>与<router-link>的实现
history: 路由的封装方式,此router 下的model : history,hash,abstract
util: 各种功能函数,比较重要的是 path.js,route.js
create-matcher: 在VueRouter---> createMatcher() 创建匹配规则
create-route-map: 在VueRouter --->createMatcher() 创建匹配规则
index: 插件入口,即 VueRouter 构造函数
install: 插件安装方式,即在Vue beforeCreate生命周期时,vue-router开始初始化。
(三)VueRouter的定义及自启动
vue-router 插件的启用是自动启用的,与 vuex 插件启用方式是不同的。
整个Index大致结构如下:
主要做了三件事:
1、定义VueRouter对象,包括 私有变量、构造函数以及原型方法。
2、给插件对象增加 install 方法用来安装插。
3、浏览器环境且Vue存在 则 自动使用插件,进行一系列初始化(Vuex则是在 Store 实例化时启动)。
VueRouter的构造函数主要干了两件事:
1、通过 createMather() ,根据用户路由配置规则生成
(1) 根据path 对应的路由记录
(2) 根据name对应的路由记录 map
返回的是两个函数 match() 以及 addRoutes(),方便后续调用匹配相应规则。
2、根据传入的model (默认是‘hash'方式)实例化具体的 history
(四)VueRouter的启动
注:本文内容来自互联网,旨在为开发者提供分享、交流的平台。如有涉及文章版权等事宜,请你联系站长进行处理。