vue实际应用vue-router

当从不一样组件进入同一个组件的时候,想要作对不一样组件作出对应的改变使用

watch: {
    '$route' (to, from) {
      // 对路由变化做出响应 写对应的业务逻辑便可...
    }
  }
  或者
    beforeRouteUpdate (to, from, next) {
   // 对路由变化做出响应 写对应的业务逻辑便可...
    // don't forget to call next() //想进入下个路由调用next(); } 复制代码

路由钩子函数的用处

router.beforeEach((to, from, next) => {
  let memberRole = Vm.$cookie('memberRole');
  //在全局定一个权限判断的钩子,经过获取的cooike值来判断身份
  Vm.$bus.memberRole = memberRole;
      if(to.fullPath==='/memberRole'){

        if(memberRole==='1'){
          //超管
          next({ path: '/superAdmins' })
          // vueRouter.push({name: '/superAdmins'})
        }else if(memberRole==='2'){
          //平台
          next({ path: '/platformPrent' })
          // vueRouter.push({name: 'login'})
        }else if(memberRole==='3'){
          //商家
          next({ path: '/superPrent' })
        }else{
          // vueRouter.push({name: 'login'})
          //普通用户
          next()
        }
      }else{
        next()
      }
});

router.afterEach((to, from) => {
 
 // 同时在全部组件内守卫和异步路由组件被解析以后,解析守卫就被调用
})
//独享守卫
const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ... 只针对foo进行监听
      }
    }
  ]
})
//组件内的路由钩子
const Foo = {
  template: `...`,
  beforeRouteEnter (to, from, next) {
    //进入前实例前阶段
    // 不!能!获取组件实例 `this`
    // 由于当守卫执行前,组件实例还没被建立
  },
  beforeRouteUpdate (to, from, next) {
    //从不一样路由跳转来的监听
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 能够访问组件实例 `this`
  }
}
总结 路由钩子就是用来判断不一样状态的一种手段。相似看门的有啥事能够先问他,由他转告以后才能进行操做
复制代码

官方解释的解析流程

  • 导航被触发。
  • 在失活的组件里调用离开守卫。
  • 调用全局的 beforeEach 守卫。
  • 在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
  • 在路由配置里调用 beforeEnter。
  • 解析异步路由组件。
  • 在被激活的组件里调用 beforeRouteEnter。
  • 调用全局的 beforeResolve 守卫 (2.5+)。
  • 导航被确认。
  • 调用全局的 afterEach 钩子。
  • 触发 DOM 更新。
  • 用建立好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数。

实际开发根本用不上,可是面试的毛病多爱问,想答就答不想答就不答,爱咋咋地html

路由嵌套

const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User,
      children: [
        {
          // 当 /user/:id/profile 匹配成功,
          // UserProfile 会被渲染在 User 的 <router-view> 中
          path: 'profile',
          component: UserProfile
        },
        {
          // 当 /user/:id/posts 匹配成功
          // UserPosts 会被渲染在 User 的 <router-view> 中
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
})
复制代码

主要作后台系统不一样角色嵌套的子集vue

路由懒加载

const Foo = () => import('./Foo.vue')
//分块懒加载
const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue')
const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue')
const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue')

对于优化项目比较有用,分块懒加载,打包好拆分
复制代码

vue-router路由的两种模式

vue-router 默认 hash 模式 —— 使用 URL 的 hash 来模拟一个完整的 URL,因而当 URL 改变时,页面不会从新加载。node

若是不想要很丑的 hash,咱们能够用路由的 history 模式,这种模式充分利用 history.pushState API 来完成 URL 跳转而无须从新加载页面。
和后台配合更改配置,若是使用ssr的时候须要用到这种模式。线上环境最好也改为这样看起来比较好用户输入带井号很丑。webpack

history路由模式与后台的配合

# nginx
location / {
  try_files $uri $uri/ /index.html;
}
# node 
const http = require('http')
const fs = require('fs')
const httpPort = 80

http.createServer((req, res) => {
  fs.readFile('index.htm', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.htm" file.')
    }

    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    })

    res.end(content)
  })
}).listen(httpPort, () => {
  console.log('Server listening on: http://localhost:%s', httpPort)
})
复制代码

vue-router的动态路由匹配以及使用

路由的动态匹配有不少种,能够经过跳转到路由所传的参数来动态改变路由状态,能够经过导航守卫监听路由状态,匹配的优先级就按照路由的定义顺序:谁先定义的,谁的优先级就最高。nginx

{
  // 会匹配全部路径
  path: '*'
}
{
  // 会匹配以 `/user-` 开头的任意路径
  path: '/user-*'
}

复制代码

router-link组件及其属性

1.":to" 属 性web

至关于a标签中的"herf"属性,后面跟跳转连接所用面试

Homevue-router

Home 2."replace" 属 性bash

replace在routre-link标签中添加后,页面切换时不会留下历史记录cookie

3."tag" 属 性

具备tag属性的router-link会被渲染成相应的标签

Home

  • Home
  • 此时页面的li一样会起到a连接跳转的结果,vue会自动为其绑定点击事件,并跳转页面

    4."active-class" 属 性

    这个属性是设置激活连接时class属性,也就是当前页面全部与当前地址所匹配的的连接都会被添加class属性

    Home active-class属性的默认值是router-link-active,因此若是没有设置,就会被渲染为这个class

    能够在router.js里面设置

    const router = new VueRouter({ mode: 'hash', linkActiveClass: 'u-link--Active', // 这是连接激活时的class }) 5."exact" 属 性

    开启router-link的严格模式

    home 上面这个标签若是不加exact属性,则会在vue2.leenty.com/article页面下也会被匹配到, 这却不是咱们的本意,在加了这个属性后就会正确的匹配到vue2.leenty.com下

    路由传参

    1,this.$router.push({ path: '/news', query: { userId: 123 }});  this.$route.query.userId
    2, <router-link :to="{ name: 'news', params: { userId: 1111}}">click to news page</router-link> <router-link :to="{ path: '/news', query: { userId: 1111}}">click to news page</router-link>
    3,props: ['id'],传参,可使用对象,布尔,函数模式 耦合性下降
    复制代码