Vue Router 学习及demo

Vue Router :

router的api:

https://router.vuejs.org/zh/api/

路由管理器,功能有:

  • 嵌套的路由/视图表
  • 模块化的、基于组件的路由配置
  • 路由参数、查询、通配符
  • 基于 Vue.js 过渡系统的视图过渡效果
  • 细粒度的导航控制
  • 带有自动激活的 CSS class 的链接
  • HTML5 历史模式或 hash 模式,在 IE9 中自动降级
  • 自定义的滚动条行为

子路由:

–js代码:注意:children路由中的path不需要添加‘/’
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

// 定义路由组件
const first = { template: '
This is first.
' } const second = { template: '
This is second.
' } const Home = { template: '
This is home.
' } const firstChild = { template: '
firstChild内容
' } const secondChild = { template: '
secondChild内容
' } const childRouter = { template: `

组件

` } //定义router实例,配置路由的路径及对应的组件 const router = new Router({ mode: 'history', base: __dirname, //可以将routes分离出去单独定义为一个变量,引入进来即可 routes: [ { path: '/', component: Home }, { path: '/first', component: childRouter, children:[ { path: '/', component: first}, { path: 'first', component: firstChild}, { path: 'second', component: secondChild} ] }, { path: '/second', component: second } ] }) // 创建和挂载根实例 new Vue({ router, template: `

Named Routes

  1. /
  2. first
    1. firstChild
    2. secondChild
  3. bar
` }).$mount('#app')

–html代码:


    

Named Routes

– 展示:
Named Routes
/
first
firstChild
secondChild
bar
组件
This is first.

路由中参数的传递:

  • 通过$route.name获取路由的name参数
  • 通过$route.params获取路由传递的参数
const firstChild = { template: '
firstChild内容
' } const secondChild = { template: '
secondChild内容 {{ $route.params.id }}
' } const childRouter = { template: `

组件

` } //定义router实例,配置路由的路径及对应的组件 const router = new Router({ mode: 'history', base: __dirname, //可以将routes分离出去单独定义为一个变量,引入进来即可 routes: [ { path: '/', name: 'Home', component: Home }, { path: '/first', component: childRouter, children:[ { path: '/', name: 'First', component: first}, { path: 'first', name: 'First-Child', component: firstChild}, { path: 'second', name: 'Second-Child', component: secondChild} ] }, { path: '/second', name: 'Second', component: second } ] }) // 创建和挂载根实例 new Vue({ router, template: `

Named Routes

{{ $route.name }}

  1. /
  2. first
    1. firstChild
    2. secondChild
  3. bar
` }).$mount('#app')

路由表的组件群,同一个路由对应多个组件:

注意:

  • component需要用复数形式:components
// 定义路由组件
const first = { template: '
This is first.
' } const Home = { template: '
This is home.
' } const a = { template: '
This is a compenent.
' } const b = { template: '
This is b compenent.
' } const c = { template: '
This is c compenent.
' } //定义router实例,配置路由的路径及对应的组件 const router = new Router({ mode: 'history', base: __dirname, //可以将routes分离出去单独定义为一个变量,引入进来即可 routes: [ { path: '/', name: 'Home', component: Home }, { path: '/first', name: 'First', components: { /* 注意components单词用复数形式 */ /* 该路由路径对应了三个组件 */ default: a, left: b, right: c }}, ] }) // 创建和挂载根实例 new Vue({ router, template: `

Named Routes

{{ $route.name }}

  1. /
  2. first
/* 组件群放置的位置,默认组件和具有相应name属性的组件 */
` }).$mount('#app')

路由传参:

const router = new Router({
  mode: 'history',
  base: __dirname,
  //可以将routes分离出去单独定义为一个变量,引入进来即可
  routes: [
    { path: '/' },
    /* 对应有两个参数:aaa,bbb的路由 */
    { path: '/params/:aaa/:bbb'},
    /* 使用正则表达式,对应id参数为数字的路由 */
    { path: '/params-regex/:id(\\d+)'}
  ]
})

// 创建和挂载根实例
new Vue({
  router,
  template: `
    
  • /
  • /params/111/222
  • /params-regex/111

{{ $route.params.aaa }}

{{ $route.params.bbb }}

id: {{ $route.params.id }}

        
          {{ JSON.stringify($route, null, 2) }}
        
      
` }).$mount('#app')

query:

// 定义路由组件
const Home = {template: '

Home

'} const users = { template: `

Users

` } const user = { template: `
/* 输出query中的内容 */ {{ $route.params.username }} -- {{ $route.query.key }}
` } //定义router实例,配置路由的路径及对应的组件 const router = new Router({ mode: 'history', base: __dirname, //可以将routes分离出去单独定义为一个变量,引入进来即可 routes: [ { path: '/', naem: 'Home', component: Home }, { path: '/users', component: users, children: [ /* 传递username参数 */ {path: ':username', name: 'user', component: user} ] } ] }) // 创建和挂载根实例 new Vue({ router, template: `
  1. /
  2. first
    1. query
` }).$mount('#app')

路由重定向:

// 定义路由组件
const sdfsf = {
  template: `
    

This is sdfsf.

` } const first = { template: '
This is first.
' } const second = { template: '
This is second.
' } const Home = { template: '
This is home.
' } const firstChild = { template: '
This is firstChild.
' } const a = { template: '
This is a compenent.
' } const b = { template: '
This is b compenent.
' } const c = { template: '
This is c compenent.
' } //定义router实例,配置路由的路径及对应的组件 const router = new Router({ mode: 'history', base: __dirname, //可以将routes分离出去单独定义为一个变量,引入进来即可 routes: [ { path: '/', name: 'Home', component: Home }, { path: '/first', name: 'First', component: sdfsf, children: [ { path: '/', component: first }, { path: 'firstChild', name: 'First-Child', component: firstChild}, /* 将secondChild重定向到firstChild,通过如下两种方式均可 */ /* { path: 'secondChild', redirect: { name: 'First-Child'}} */ { path: 'secondChild', redirect: 'firstChild'} ] }, { path: '/aaa/:id', component: second }, { path: '/bbb/:id', redirect: '/aaa/:id' }, /* 根据参数值,来设置重定向的路径 */ { path: '/ccc/:id', redirect:xxxx => { const { hash, params, query } = xxxx; if(params.id == '001') { return '/' }else{ return '/aaa/:id' } } } ] }) // 创建和挂载根实例 new Vue({ router, template: `

Named Routes

{{ $route.name }}

  1. /
  2. first
    1. firstChild
    2. secondChild
  3. /aaa/123
  4. /bbb/234
  5. /ccc/234
` }).$mount('#app')

别名:alias

{path: '/second', name 'Second', component: second, alias: '/gogo' }
  • gogo
  • 通过访问上面的 '/gogo'路径即可访问'/second'路由。 --数组:同时为一个路由起多个别名 { path: 'firstChild', name: 'First-Child', component: firstChild, alias: ['/gogo', '/haha'] },

    路由的过渡动画:

    
    	
    
    
    --css:
    .fade-enter-active, .fade-leave-active {
    	transition: opacity 0.5s
    }
    .fade-enter, .fade-leave-active {
    	opacity: 0
    }
    

    监控动画,watch:

    new Vue({
        router,
        data() {
          return {
              nameVal: 'fade1'
          }
        },
        template: `
            

    {{ $route.name }}

    • /
    • parent
    `, watch: { '$route'(to, from){ if (from.path == '/parent') { this.nameVal = 'fade1' } else { this.nameVal = 'fade2' } } } }).$mount('#app') --class代码: .fade1-enter-active, .fade-leave-active { transition: opacity 0.5s } .fade1-enter, .fade-leave-active { opacity: 0 } .fade2-enter-active, .fade-leave-active { transition: opacity 0.5s } .fade2-enter, .fade-leave-active { opacity: 0; background-color: red; color: blue; }

    定义404路由,当路由不存在时的显示页面:

    --定义404路由:
    const Page404 = {
      template: `
          

    This is 404.

    ` } --将'/*'路径与404路由对应: const router = new Router({ mode: 'history', base: __dirname, routes: [ { path: '/', component: Home }, { path: '/parent', component: parent}, /* 404的路径一定要放在最后面 */ { path: '/*', component: Page404}, ] }) --例子:未定义的路由
  • where is page
  • 利用路由引入vue组件:

    --根据文件路径来引入:
    import Parent from '../components/transition.vue'
    
    --在路由中定义:
    const router = new Router({
        mode: 'history',
        base: __dirname,
        routes: [
            { path: '/', component: Home },
            { path: '/xxx', component: Parent},
        ]
    })
    
    创建实例:当点击 'where is page'链接时,即显示引入的vue组件模板
    
  • where is page
  • 配置路径:@代替’src’

    -- 如下:将src路径配置为'@',将components路径配置为'cmp'
    resolve: {
        extensions: ['.js', '.vue', '.json'],
        alias: {
          'vue$': 'vue/dist/vue.esm.js',
          '@': resolve('src'),
          "cmp":resolve('src/components')
        }
      },
      
    --使用components路径:
    { path: '/', component: ()=>import('cmp/HelloWorld') }
    等价于:
    { path: '/', component: ()=>import('../components/HelloWorld') }
    

    路由守卫:

    全局前置守卫:next()方法必须调用,不然无法跳转;next(false)或不定义,路由不会跳转
    router.beforeEach((to, from, next) => {
        /* to:即将要进入的目标 路由对象 */
        /* from: 当前导航正要离开的路由 */
        console.log(to)
        console.log(from)
        next()
    })
    
    全局后置守卫:没有next函数
    router.afterEach((to, from) => {
      // ...
    })
    
    路由独享前置守卫:
    const router = new Router({
        routes: [
            { path: '/', component: ()=>import('cmp/HelloWorld') },
            { path: '/parent', component: parent,
                beforeEnter: (to, from, next) => {
                    // next('/parent1')  --等同于下面代码:点击'/parent'会跳转到'/parent1'路由
                    next({ path: 'parent1' })
                }
            }
        ]
    })
    
    组件内守卫:

    参考官网:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html#%E7%BB%84%E4%BB%B6%E5%86%85%E7%9A%84%E5%AE%88%E5%8D%AB

    编程式导航:前进后退首页query按钮

    
    
    

    你可能感兴趣的:(Vue)