Update Router
parent
ef55737c95
commit
72ae70dc16
151
Router.md
151
Router.md
|
@ -22,3 +22,154 @@ const router = createRouter({
|
|||
]
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
## 路由模块5大方法
|
||||
|
||||
### 1. createRouter()
|
||||
> 这是创建路由中间件的方法, 传入一个包含`history`和`routes`的对象。
|
||||
|
||||
### 2. createWebHashHistory()
|
||||
> 创建`hash`路由, 传入createRouter的参数之一。
|
||||
|
||||
### 3. createWebHistory()
|
||||
> 创建`history`路由, 传入createRouter的参数之一。
|
||||
|
||||
### 4. getRouter()
|
||||
> 这是用来获取当前的路由实例的方法, 通常情况下不需要用到这个方法, 基于`wkit`开发的组件, 可直接在内部通过`this.$router`获取。这个方法, 是给其他不是基于`wkit`的组件用的。
|
||||
|
||||
### 5. getCurrentPage()
|
||||
> 这是用来获取当前页面的路由信息的方法, 跟上面的方法一样, 只在非`wkit`组件才需要用。`wkit`组件内部可通过`this.$router.route`获取。
|
||||
|
||||
|
||||
## 路由实例属性 & 方法
|
||||
|
||||
|
||||
### .route
|
||||
> 只读属性, 为当前页面的路由信息。
|
||||
|
||||
|
||||
### .addRoute()
|
||||
> 一般来说, 路由页面, 在创建路由的时候已经添加好了, 在有必要的时候, 可调用这个方法追加路由页面。
|
||||
|
||||
```js
|
||||
|
||||
$router.addRoute({
|
||||
path: '/foo',
|
||||
name: 'wc-foo'
|
||||
})
|
||||
|
||||
```
|
||||
|
||||
|
||||
### .go(delta)
|
||||
> 同原生的`history.go()`, 可通过传参实现向前/向后跳转多少个页面。
|
||||
|
||||
```js
|
||||
|
||||
$router.go(1) // 前进一个页面(如果有的话)
|
||||
$router.go(-1) // 后退一个页面(如果有的话)
|
||||
|
||||
```
|
||||
|
||||
### .back()
|
||||
> 等价于 `.go(-1)`
|
||||
|
||||
### .forward()
|
||||
> 等价于 `.go(1)`
|
||||
|
||||
|
||||
### .push(path)
|
||||
> 新页面跳转, path可以一字符串格式, 也可以是对象。
|
||||
|
||||
```js
|
||||
|
||||
|
||||
$router.push('/foo/bar')
|
||||
$router.push('/foo/bar?goo=123')
|
||||
|
||||
$router.push({
|
||||
path: '/foo/bar'
|
||||
})
|
||||
|
||||
$router.push({
|
||||
path: '/foo/bar',
|
||||
query: { goo: 123 }
|
||||
})
|
||||
|
||||
```
|
||||
|
||||
|
||||
### .replace(path)
|
||||
> 与`.push()`方法一样, 都是新页面跳转, 区别是, `replace()`跳转会替换当前路由。
|
||||
|
||||
|
||||
|
||||
### .beforeEach(callback`<Function>`)
|
||||
> 路由守卫方法。可以在每个路由跳转之前, 做一些额外的逻辑。不满足逻辑时, 可选择阻止页面跳转。
|
||||
|
||||
|
||||
|
||||
```js
|
||||
|
||||
import { createRouter, createWebHistory } from 'wkitd'
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(), // 默认createWebHashHistory
|
||||
routes: [
|
||||
{
|
||||
path: '/',
|
||||
name: 'wc-home' // 必须为页面组件的标签名
|
||||
},
|
||||
{
|
||||
path: '/about',
|
||||
name: 'wc-about',
|
||||
component: () => import('./views/about.js')
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
|
||||
router.beforeEach(function (prev, next, done) {
|
||||
|
||||
// console.log(prev, next)
|
||||
// prev 即为上一页的路由信息
|
||||
// next 为下一页的路由信息
|
||||
// 这里可以做任意逻辑处理, 完成执行 done() 即可
|
||||
done()
|
||||
})
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
Loading…
Reference in New Issue