重学vue 2.0

in 前端 with 0 comment

前情提要

主要基于 vue-admin-element-ui来进行辅助学习

为什么用它?

因为它相对来说复杂,实用,入手快,能快速得到成就感,同时在以后都可以用于生产环境进行

第一天先学习下vue-router,主要是掌握一下基本的用法

例如

这里的笔记,只是我个人的记录,因为我学习过,需要性的复习

配置别名

resolve: {
  alias: {
    '~': resolve(__dirname, 'src')
  }
}

vue-router

导航

html

# <router-link> 默认会被渲染成一个 `<a>` 标签
<router-link to="/foo">Go to Foo</router-link>

路由跳转

this.$router.push('/')
this.$router.go(-1)

活动的路由

会自动设置class : router-link-active

api学习

具体例子:见 https://router.vuejs.org/zh/api/#replace

routes配置项

interface RouteConfig = {
  path: string,
  component?: Component,
  name?: string, // 命名路由
  components?: { [name: string]: Component }, // 命名视图组件
  redirect?: string | Location | Function,
  props?: boolean | Object | Function,
  alias?: string | Array<string>,
  children?: Array<RouteConfig>, // 嵌套路由
  beforeEnter?: (to: Route, from: Route, next: Function) => void,
  meta?: any,

  // 2.6.0+
  caseSensitive?: boolean, // 匹配规则是否大小写敏感?(默认值:false)
  pathToRegexpOptions?: Object // 编译正则的选项
}

快捷操作

router.push(location, onComplete?, onAbort?)
router.push(location).then(onComplete).catch(onAbort)
router.replace(location, onComplete?, onAbort?)
router.replace(location).then(onComplete).catch(onAbort)
router.go(n)
router.back()
router.forward()

# 添加一个路由配置
router.addRoutes(routes: Array<RouteConfig>)

# 捕获路由错误
router.onError(callback)

$route.path
$route.params
$route.query
$route.hash :当前路由的 hash 值 (带 #) ,如果没有 hash 值,则为空字符串
$route.fullPath :完整路由
$route.matched : 路由纪律
$route.name
$route.redirectedFrom :如果存在重定向,即为重定向来源的路由的名字

导航守卫(类似于中间键一样的东西)

# 全局前置守卫
router.beforeEach((to, from, next) => {
  // ...
})

全局解析守卫

在 2.5.0+ 你可以用 router.beforeResolve 注册一个全局守卫。这和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。

全局后置钩子

router.afterEach((to, from) => {
  // ...
})

组件内守卫

const Foo = {
  template: `...`,
  beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
  },
  beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
  }
}

进度

vue-router复习大概耗时 一个半小时

参考文章

https://juejin.im/post/591aa14f570c35006961acac

手摸手,带你用vue撸后台 系列二(登录权限篇)

Comments are closed.