跳至主要內容

路由

Emilia Zhen大约 4 分钟vue

路由

后端路由:监听不同的URI(地址),做不同的请求处理。 前端路由:是专门为SPA(单页应用程序)服务,也是监听不同的地址,切换不同的的地址,做页面的切换

  1. 引入vue-router.js,创建组件模版对象
<template id="indexTpl">
  <h1>这是首页</h1>
</template>
<template id="productTypeTpl">
  <div>
    <h2>这是产品{{ $route.params.id }}:{{ productName }}</h2>
    <router-link :to="'/productType/' + $route.params.id + '/list'">Show</router-link>
    <router-link :to="{ name: 'showList' }">AAA</router-link>
    <router-view></router-view>
  </div>
</template>
const index = Vue.component('index', {
   template: '#indexTpl',
     data() {
            return {msg: '首页'
      }
   }
})

const productType = Vue.component('productType', {
     template: '#productTypeTpl',
     data() {
             return {productName: ''}
      },
methods: {...},
created () {...},
watch: {
  '$route' (from, to) {
       console.log(from);
       console.log(to);
// console.log(this.$route);
     switch (to.params.id) {
         case '01':   this.productName = '大虾';   break;
         case '02':    this.productName = '螃蟹';    break;
         case '03':this.productName = '扇贝';break;
         default:this.productName = ''break;
      }
   }
}
})
  1. 创建路由对象并配置路由规则
const router = new VueRouter({
  routes: [
    {
      path: '/index',
      component: index,
    },
    { path: '/productType/:id', component: productType, children: [{ name: 'showList', path: 'list', component: showList }] },
    { path: '/', redirect: '/index' },
    { path: '*', redirect: '/index' },
  ],
})
  1. 将创建处理的路由对象和 Vue 进行绑定
new Vue({
  el: '#app',
  data: {
    msg: 'app',
    path: '',
  },
  router,
})
  1. 使用<router-view></router-view>进行占位
<router-view></router-view>

children子路由对象中的path不能带/
子路由的组件不能直接显示在父路由对应的router-view
子路由的组件需要显示在父路由对应的模版中,也就是在父路由组件的模版中需要添加一个router-view
想要跳转到子路由对应的组件,需要router-linkto属性中将父路由的path和子路由的path拼接

this.$router.push({ name: 'cookBook' })
this.$router.push('/product_type/11/cook_book')

this.$router就是创建的VueRouter实例,专用来挂载vue-router对象
this.$routeroutes数组中的每一个路由对象
routesVue-Router实例内部的一个属性,用来保存所有的路由规则

路由重定向

{path:'/',redirect:'/index'}
{path:'*',redirect:'/index'}

在路由规则中配置redirect属性可以使路由进行内部切换,当访问path中的路径时,会默认跳转到redirect中指定的路径中去

嵌套路由

  1. 在父路由内部使用children属性配置子路由规则,子路由规则对象中的path属性不要/,定义好component组件
{path:'/productType/:id',component:productType,
children:[{name:'showList',path:'list',component:showList}]},
  1. 在父路由规则对应的组件模版添加<router-view>用于显示子路由规则对应的组件
<template id="productTypeTpl">
  <div>
    <h2>这是产品{{ $route.params.id }}:{{ productName }}</h2>
    <router-view></router-view>
  </div>
</template>
  1. <router-link>中设置跳转路径(将父路由和子路由的 path 拼接)
<router-link :to="'/productType/'+$route.params.id+'/list'">Show</router-link>

<roter-link>
  <router-link to="hone">home</router-link>
  <router-link :to="{path:'home'}">home</router-link>
  //命名的路由,this.$route.params获取参数
  <router-link :to="{name:'user',params:{userId:123}}">user</router-link>
  //带查询参数 /register?plan=private 在组件内部使用this.$route.query获取参数
  <router-link :to="{path:'register',query:{plan:'private'}}">register</router-link>
  //replace属性true|false 不留下history记录
  <router-link to="home" replace>home</router-link>
  //append属性ture|false 追加路径
  <router-link to="home" apped>home</router-link>
  //tag属性string 设置渲染标签
  <router-link to="/foo" tag="li">foo</router-link>
</roter-link>

linkActiveClass 路由高亮

new VueRouter({ linkActiveClass: 'mylink' })
// 被选中会有一个类名叫mylink

拦截器

除登录请求外,其他所有请求发送都必须保证请求头中有登录成功返回 token 值,所以需要使用拦截器给请求添加Authorization,请求头中Authorization名字是后台规定的

axios.interceptors.request.use(
  function (config) {
    let token = localStorage.getItem('token')
    config.headers['Authorization'] = token
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

路由守卫

对于需要登录的页面访问前需要判断是否已经登录,使用路由导航钩子进行拦截
router/index.js中使用路由全局守卫拦截所有的路由跳转

router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('token')
  if (token) {
    next()
  } else {
    if (to.path !== '/login') {
      next({ path: '/login' })
    } else {
      next()
    }
  }
})

返回按钮

this.$router.go(-1)
watch:{
    // 监听路由地址
    '$route.path':function(newVal){
          if(newVal === '/home'){
              this.flag = false;
          }else{
               this.flag = true;
           }
      }
      // 监听路由对象 '$router':function(to,from){}
}

动态路由

这种方式添加的路由规则是直接存储在内存中,只要页面刷新就会丢失,需要本地存储

this.$router.addRoutes([{ ...路由规则 }])

linkActiveClass用来设置当前被激活的路由样式,默认属性值是router-link-active

var router = new Router{
   linkActiveClass:'mui-active'
}

按需加载组件

Const User = r => require.ensure([],()=>r(require('@/componts/User.vue')),'chunkname1')

父组件访问子组件:使用$children$refs 子组件访问父组件:使用$parent 子组件访问根组件:使用$root