vue-router学习笔记

vue-router


 go Home 


 



//组件
var Home = {
  template:'

我是主页

' } var User = { tempalte:'

用户

' } //配置路由 const routes = [ { path:'/home', //匹配命名路由 components:{ a:Bar, b:Baz }, //路由嵌套,子路由 /home/user children:[ {path:'user',component:User} ] }, //重定向 {path:'*',redirect:'/home'} ] //生成路由实例 const router = new VueRouter({ mode:'history', //history模式区别于hash,不会生成很丑的hash routes // (缩写)相当于 routes:routes }) //挂载到vue上 new Vue({ router }).$mount('#app')

动态路由匹配

//自动匹配/user/xxx到 User组件
  {path:'/user/:id',component:'User'}
//当匹配到该路由的时,后面的id参数值会被设置到this.$route.params

const User = {
  template:'...',
  watch:{
    '$route'(to,from){
      // 对路由变化做出响应
    }
  }
}

编程式路由

点击等同于调用router.push(…),会像history添加记录。

// 字符串
router.push('home')

// 对象
router.push({path:'home'})

// 命名的路由,变成/user/123
router.push({path:'user',params:{userId:123}})

// 带查询参数,变成 /user?id=123
router.push({path:'user',query:{id:123}})

// 跟router.push的区别就是,它不会像history添加新记录,而是替换掉当前的history记录。
router.replace(location);

// 在history记录中向前或者向后退多少步
router.go(n)

路由懒加载

// 将组件定义成异步组件
const Foo = resolve => {
  require.ensure(['./Foo'],() => {
    resolve(require('./Foo'))
  })
}

// 一样的路由配置
const routes = [
  {path:'/foo',component:Foo}
]

你可能感兴趣的:(vue-router学习笔记)