vue-router的使用方法介绍

2018-6-19    seo达人

如果您想订阅本博客内容,每天自动发到您的邮箱中, 请点这里

vue-router

对于大多数单页面应用,都推荐使用官方支持的 vue-router 库。

学习网址:https://router.vuejs.org/installation.html#direct-download-cdn

提示:本篇博客仅仅介绍搭建项目之后,再下载vue-router的情况,并非搭建项目是直接引入vue-router。

一、安装方法(npm方式)

在终端运行以下指令

[html] view plain copy
  1. npm install vue-router  

注意:--save 与 --save-dev 的区别

--save(可以省略) 下载的第三方依赖到package.js中的dependencies。

--save-dev 下载开发时依赖,指环境配置,下载到package.js中的devDependencies,webpack、bable等等均属于开发

时依赖。

二、导入与使用

vue-router下载之后,需要在入口文件main.js导入,具体做法如下:

[javascript] view plain copy
  1. Vue.use(VueRouter);  
  2. Vue.use(VueAxios, axios);  
  3.   
  4. // routes:数组,在该数组中配置所有的路由;  
  5. const routes = [  
  6.   {path:'/',component:myHome,name:'home'},  
  7.   {path:'/product/:productName/:price',component:myProduct,name:'product'}  
  8. ];  
  9. // 创建router实例  
  10. const router = new VueRouter({  
  11.   routes  
  12. });  
  13. /* eslint-disable no-new */  
  14. new Vue({  
  15.   el: '#app',  
  16.   // 引入到根实例中才可以使用导航功能  
  17.   router,  
  18.   components: {App},  
  19.   template: '<App/>',  
  20.   data(){  
  21.     return {  
  22.   
  23.     }  
  24.   }  
  25. })  

三、官网介绍使用步骤

网址:https://router.vuejs.org/zh/guide/#javascript

[javascript] view plain copy
  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')  
  30.   
  31. // 现在,应用已经启动了!  

蓝蓝设计www.lanlanwork.com )是一家专注而深入的界面设计公司,为期望卓越的国内外企业提供卓越的UI界面设计、BS界面设计 、 cs界面设计 、 ipad界面设计 、 包装设计 、 图标定制 、 用户体验 、交互设计、 网站建设 平面设计服务




分享本文至:

日历

链接

blogger

蓝蓝 http://www.lanlanwork.com

存档