hash: 使用 URL hash 值来做路由。支持全部浏览器,包括不支持 HTML5 History Api 的浏览器。 /#homejavascript
history: 依赖 HTML5 History API 和服务器配置。【须要后端支持】 /homehtml
yarn add vue-router -S
引入第三方的依赖包, 并注册路由
```javascript
import Vue from 'vue'
import VueRouter from 'vue-router'vue
javascript const routes = [ { path: '/home', component: Home }//每个对象就是一个路由 ] const router = new VueRouter({ routes//路由表 必写的 })
export default router
javascript import router from './router/index.js' new Vue({ router, render: (h) => App }).$mount('#app')
<router-view />
javascript const routes = [ { //咱们要求这个路由的配置要放在路由表的最上方 path: '/', redirect: '/home' } ]
javascript const routes = [ { path: '/', redirect: '/home' //重定向 }, { path: '/home', component: Home }, { path: '/list', component: List }, { path: '/detail', component: Detail }, { path: '/login', component: Login }, { path: '/register', component: Register }, { path: '/user', component: User }, { path: '/shopcar', component: Shopcar }, { path: '/error', component: Error }, { //这个就是错误路由匹配, vue规定这个必须放在最下面,它必须将上面的路由全找一遍,找不到才用当前这个 path: '**', redirect: '/error' } ]
vue路由模式的肯定 mode
1. 若是你使用的是 hash , 那么a标签就能够了、
2. 若是你使用 history , 那么咱们最好将a标签改为 router-link 这个组件
- router-link 这个组件 身上必需要有一个 to 属性
- router-link 这个组件身上加一个 keep-alive属性能够进行浏览器缓存java
javascript const routes = [ { path: '/shopcar', component: Shopcar, children: [ { path: 'yyb', //不写 / component: Yyb } ] } ]
命名路由android
做用: 就是简写路径了vue-router
{ path: '/shopcar', component: Shopcar, //子路由 children: [ { path: 'yyb', // 容易犯错点 /yyb X component: Yyb, name: 'yyb' //命名路由 }, { path: 'junge', component: Junge } ] },
使用:编程
<router-link :to = "{name:'yyb'}"/>
// vue.config.js中能够默认直接使用 http-proxy-middleware module.exports = { devServer: { proxy: { '/douban': { // /douban 是一个标记 target: 'http://api.douban.com', // 目标源 changeOrigin: true, // 修改源 pathRewrite: { '^/douban': '' } }, '/siku': { target: 'https://android.secoo.com', changeOrigin: true, pathRewrite: { '^/siku': '' } } } } }
<router-link :to = "{name: 'list',params: {id: xxx}, query: {xxx:xxx}}"></router-link>
id: this.$route.params.id query: this.$route.query.xxx
this.$router.push('/home')
router.beforeEach(fn)
next(vm => { //vm指的就是组件 const result = JSON.parse(res.data.slice(7,-1)).rp_result.categorys vm.$set(vm.category,'categorys',result) })
this
router.beforeEach((to,from,next)=>{ const name = localStorage.getItem('name') if( name || to.path === '/login' ){ //若是有 / --> /home next() }else{ next('/login') } })
业务: 当进入mine页面的时候, 要判断用户是否登陆,若是没有登陆,跳转登陆页后端
路由懒加载api