1、vue-router
- 安装方式
- npm/cnpm:(个人偏向于cnpm)
npm/cnpm install vue-router --save-dev
- bower:
bower install vue-router --save-dev
- 手动编译:省略
- npm/cnpm:(个人偏向于cnpm)
- 基本使用
- 概念:
后端路由:根据不同的url返回不同的内容(node) 前端路由:根据不同的hash返回不同的组件(Vue生成的项目叫做单页应用(SPA),单页面应用的特点就是可以在改变URL不重新请求页面的情况下更新页面视图。) - 类型:
一、经常使用,无兼容性问题的方式hash 二、history方式history.pushState(stateObj,'page2','2.html');----页面重新加载了吗?为什么url地址栏发生变化,显示为2.html,但并不会跳转到2.html页面上,也不会检查这个路径是否存在,它只是成为浏览历史中的最新记录,假定你访问了google.com,然后点击了倒退按钮,页面的url将显示为2.html,但是内容还是原来的1.html,再点击一次,url变为1.html,内容不变,总之,这个方法不会触发页面刷新,只会导致history对象发生变化,地址栏会有反应三、node下的默认实现方式abstract
import Vue from 'vue' 在router文件下的index.js文件中 import Router from 'vue-router' import { routes } from './router' 在router文件下的router.js文件中定义路由 Vue.use(Router)//注册 // 路由配置 const RouterConfig = { // mode: 'history', routes, }; - 路由的重定向:
redirect: { path: '/zh-CN/login' }, - 错误路由的匹配(如任意路径或者 404 Not Found)
{ path: '**', // 错误路由,使用通配符,并且此路由应该放到最后 redirect: { path: '/zh-CN/login' },//重定向 } - 路由元信息:路由中的meta字段;
- 路由视图:
<router-view></router-view>相当于一个占位符,匹配到的组件展示到其中去
- 路由导航:
- 使用<router-link> 创建 a 标签来定义导航链接
<router-link to="/path" tag="">标签</router-link> 默认渲染为一个a标签,通过tag属性可以改变标签,仍然可以跳转
- 使用 router.push 方法(编程式导航)
View Code
一、跳转 1、this.$router.push('/list/' + type); 2、this.$router.push({path : '/list/' + type}) 3、this.$router.push({//常用 name: "list", params: { a: a, b: b, c: c }, query: {//查询参数 reason: 'reason', }, }); 跳转之后进行取值 this.$route.params.a /list/a/b/c this.$route.query.reson /list?reason = reason 二、替换 this.$router.replace(‘/home’) 前进后退按钮失效,清除路由跳转的历史记录 三、前进 this.$router.go(1) === window.history.forward() 四、后退 this.$router.go(-1) === window.history.back()
- 使用<router-link> 创建 a 标签来定义导航链接
- 概念: