美文网首页让前端飞Web前端之路js
vue-router(单页面应用控制中心)常见用法

vue-router(单页面应用控制中心)常见用法

作者: Nice先生的狂想曲 | 来源:发表于2019-12-04 02:50 被阅读0次

前言

vue-router控制页面跳转,重点在于“更新视图但不重新请求页面”,并且拥有懒加载功能。


推荐配置写法(开启页面跳转至组件,懒加载)

export default new Router({
  routes: [{
    path: '/home',
    name: 'home',
    component: () => import('home.vue') //懒加载
  }]
})

之后在App.vue中插入<router-view></router-view>既可。

事件跳转

在点击等事件触发时执行方法,另外如果需要传递参数,则可以在push方法中以query: { a: '111'}

  this.$router.push( { path: '/home' } ) // 该处path对应在配置中的路径

当然也可以用 链接 的方式进行跳转

<router-link to="/home"></router-link>
动态路由
export default new Router({
  routes: [{
    path: '/home/:id',//传参,当/后面接任何字符串均可
    name: 'home',
    component: () => import('home.vue')
  }]
})

另组件内获取参数的方法

<h1>{{ $route.params.id }}</h1>
嵌套路由

当你需要只改变布局中的一部分页面时

  routes: [{
    path: '/home',
    name: 'home',
    component: () => import('home.vue')
    children: [{
      path: '/child',
      component: () => import('child.vue')
    }]
  }]

之后在home.vue中插入<router-view></router-view>既可

push() 传递参数

在事件跳转中我们说到push方法中可以query: { a: '111'}进行参数传递

  this.$router.push( { path: '/home' , query: { a: '111'}} ) 

此外我们还能用params : { a: '111'}进行传参,但是注意此时push方法不再用path,而用name,否则会有错误!

  this.$router.push( { name: 'home' , params: { a: '111'}} ) 

事实上,vue-router的用法并不仅仅只有这些,并且他有自己的钩子函数,例如可以利用beforeEach记录跳转的路径,同时如果不加入next()方法则路由无法跳转,类似于 Generator 函数的驻点

router.beforeEach(to, from, next) => {
  console.log(to.path)
  next() 
}

相关文章

网友评论

    本文标题:vue-router(单页面应用控制中心)常见用法

    本文链接:https://www.haomeiwen.com/subject/ewckgctx.html