Skip to content

Commit

Permalink
feat: router 新增 replace 能力 baidu#70
Browse files Browse the repository at this point in the history
  • Loading branch information
BUPTlhuanyu committed Oct 19, 2023
1 parent 51b3f21 commit 4e412fd
Show file tree
Hide file tree
Showing 4 changed files with 551 additions and 15 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
### 2.0.2

- [feature] 新增 router.replace 方法,支持替换 URL

### 2.0.1

- [fix] router.push 方法,当不传入 path 并且传入 query 为空时,原有的 location 中的 query 仍被保留
Expand Down
40 changes: 34 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
* Copyright 2017 Baidu Inc. All rights reserved.
*/

(function (root) {

(function (root) {
/**
* 元素选择器
*
Expand Down Expand Up @@ -279,6 +278,18 @@
return url;
}

/**
* 根据目标路径创建 hash href 路径
*
* @param {string} to 目标路径
* @returns {string} href
*/
function createHashHref(to) {
var href = location.href;
var hashIndex = href.indexOf('#');
return href.slice(0, hashIndex + 1) + to;
}

/**
* hash 模式地址监听器
*
Expand Down Expand Up @@ -340,7 +351,11 @@
if (isChanged) {
this.referrer = referrer;
this.current = url;
location.hash = url;
if (options.replace) {
location.replace(createHashHref(url));
} else {
location.hash = url;
}
}
else {
referrer = this.referrer;
Expand Down Expand Up @@ -430,7 +445,7 @@
this.referrer = referrer;
this.current = url;

history.pushState({}, '', url);
history[options.replace ? 'replaceState' : 'pushState']({}, '', url);
}

if ((isChanged || options.force) && !options.silent) {
Expand Down Expand Up @@ -643,6 +658,19 @@
this.locator.redirect(stringifyURL(url), options);
};

/**
* 替换路由 replace
*
* @param {Object|string} url 路由地址
* @param {Object?} options 重定向的行为配置
* @param {boolean?} options.force 是否强制刷新
*/
Router.prototype.replace = function (url, options) {
options = options || {};
options.replace = true
this.push(url, options);
};

/**
* 添加路由项
* 当规则匹配时,路由将优先将Component渲染到target中。如果没有包含Component,则执行handler函数
Expand Down Expand Up @@ -944,7 +972,7 @@
this.$router = customRouter;

this.data.set(
'route',
'route',
customRouter.match(
customRouter.locator.current,
customRouter.locator.referrer
Expand Down Expand Up @@ -1074,4 +1102,4 @@
root.sanRouter = main;
}

})(this);
})(this);
Loading

0 comments on commit 4e412fd

Please sign in to comment.