Vue全家桶实践(四)---vue-router

最近公司要重写运营管理系统,不想再维护之前的backbone了,赶紧要求前端整个重写。重开新坑,用了两周多撸出了第一版,收获很大。在实践中学习永远都是最高效的。趁热把学到的东西都记录总结下来,也算前端梳理一下思路。

相关博客:

  1. Vue全家桶实践(一)—vue-cli
  2. Vue全家桶实践(二)—iView
  3. Vue全家桶实践(三)—axios
  4. Vue全家桶实践(四)—vue-router
  5. Vue全家桶实践(五)—渲染函数&JSX
  6. Vue全家桶实践(六)—自定义指令(directive)

Vue-router

参考资料:文档

vue-router是vue写spa必备的官方推荐插件,使用方法很简单,看看文档就能很快上手。基础的用法就不赘述了,这里记录点值得记的东西。

过渡动画效果

直接使用vue的<transition>标签包裹起来即可:

<transition :name="transitionName">
  <router-view></router-view>
</transition>

// 接着在父组件内
// watch $route 决定使用哪种过渡
watch: {
  '$route' (to, from) {
    const toDepth = to.path.split('/').length
    const fromDepth = from.path.split('/').length
    this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'
  }
}

路由钩子的使用

vue-router有钩子,可以在其中增加许多常用的操作,比如:1.跳转之后修改页面的title;2.配合iview的loadingbar组件;3.跳转后的滚动条设置等等。

// router/routes.js
// 在router里设置mate的title属性
const routes = [
  {
    // 登陆之后的欢迎页,现在是客户管理
    path: '/welcome',
    name: 'welcome',
    component: customerManagement,
    meta: {
      title: '卖家云--首页'
    }
  }
]
// router/index.js
// 路由钩子,做一些跳转的配置
router.beforeEach((to, from, next) => {
  // 根据设置,修改页面title
  window.document.title = to.meta.title
  // LoadingBar
  // 除了登录页,其他都会有Loadingbar
  if (to.name !== 'Login') {
    iView.LoadingBar.start()
  }
  next()
})

router.afterEach(route => {
  // 跳转后滚动到顶端,目前没必要
  // window.scrollTo(0, 0)
  // LoadingBar
  // 到登录页没有loadingbar,到404是红色loadingbar
  if (route.name === 'Login') {
    return
  }
  if (route.name === '404') {
    iView.LoadingBar.error()
    return
  }
  iView.LoadingBar.finish()
})

猜你喜欢

转载自blog.csdn.net/creabine/article/details/78922058