vue.js学习总计---路由篇

一、安装

1.下载 cnpm install vue-router

2.在router/index.js引入与使用

 

import Vue from 'vue'

import VueRouter from 'vue-router'

Vue.use(VueRouter)

impport Home from './coponents/Home.vue
1.路由传参
export default new Router({
  routers:[
    {
      path: '/Home/:id', 动态路由参数,以冒号开头
      name: 'Home',
      component: Home
    },
    
    {
      path: '/',
      name: 'Home',
      component: Home
    },

  ]
})

const User = { template: '<div>User {{ $route.params.id }}</div>' } //获取路由参数
2.响应路由参数的变化
const user = {
  template: '...',
  watch:{
    '$route' (to,from){
      
    }
  }
}
或者
const Use = {
  template: '...',
  beforeRoteUpddate(to,from,next){
  
  }
}
3.嵌套路由
<div id="app">
  <router-view></router-view>
</div>
这里的 <router-view> 是最顶层的出口,渲染最高级路由匹配到的组件。同样地,一个被渲染组件同样可以包含自己的嵌套 <router-view>。例如,在 User 组件的模板添加一个 <router-view>
const User = { template: ` <div class="user"> <h2>User {{ $route.params.id }}</h2> <router-view></router-view> </div> ` }

const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User },
  { path: '/a', redirect: '/b' } //路由重定向
  { path: '/a', component: A, alias: '/b' } //路由别名
] })
const router = new VueRouter({   routes: [ { path: '/user/:id',
         component: User, 
          children: [ {
             path: 'profile',
            component: UserProfile
           },
           {
             path: 'posts',
             component: UserPosts
            } ]
         } ]
      })

4.编程式导航
// 字符串 router.push('home')
// 对象 router.push({ path: 'home' })
// 命名的路由 router.push({ name: 'user', params: { userId: 123 }})
// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
// 这里的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user

router.replace()和router.push()很像,不过不会向hisory中添加记录
router.go(n) 在history记录中向前或向后退多少步,类似window.history.go(n);

5.路由懒加载
const Foo = () => impoort('./Foo.vue); 引入的时候使用动态语法来定分块点
const router = new VueRouter({
  routes:[
    {path: '/foo,component: Foo}
  ]
})

6.路由的滚动行为
  history模式下可以使用savePosiition
  1)返回 savedPosition,在按下 后退/前进 按钮时,就会像浏览器的原生表现那样:
scrollBehavior (to, from, savedPosition) {
  if (savedPosition) {
     return savedPosition
  } else {
     return { x: 0, y: 0 }
  } }
2)模拟滚动到锚点的行为
scrollBehaior(to,from,savePosition){
  if(to.hash){
    return{
      selector:to.hash
    }
  }
}
hash模式下使用
router.beforeEach((to,from,next) => {
  window.scrollTo(0,0);
})
7.<router-link
  tag="li" //指定设置成某种标签、
  replace //设置 replace 属性的话,当点击时,会调用 router.replace() 而不是 router.push(),于是导航后不会留下 history 记录。
  appendd //设置append属性后,在当前路径前添加基路径
  active-class="" ///默认值是router-link-active
  //@click-native 绑定点击事件
  
></router-link>

8.<router-view></router-view> 该组件还可以内嵌自己的router-view组件
<transition> //动画组件
<keep-alive> //缓存组件
<router-view></router-view>
</keep-alive>
</transition>


 

posted @ 2017-12-28 18:34  动作大王  阅读(242)  评论(0编辑  收藏  举报