Skip to content

Commit 799dd50

Browse files
posvayyx990803
authored andcommitted
Fix active route matching (#1101)
Fix #1091 Fix the doc too
1 parent aad2ed6 commit 799dd50

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

docs/en/api/router-link.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@
9494

9595
- default: `false`
9696

97-
The default active class matching behavior is **inclusive match**. For example, `<router-link to="/a">` will get this class applied as long as the current path starts with `/a`.
97+
The default active class matching behavior is **inclusive match**. For example, `<router-link to="/a">` will get this class applied as long as the current path starts with `/a/` or is `/a`.
9898

9999
One consequence of this is that `<router-link to="/">` will be active for every route! To force the link into "exact match mode", use the `exact` prop:
100100

src/util/route.js

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
import { stringifyQuery } from './query'
44

5+
const trailingSlashRE = /\/?$/
6+
57
export function createRoute (
68
record: ?RouteRecord,
79
location: Location,
@@ -41,7 +43,6 @@ function getFullPath ({ path, query = {}, hash = '' }) {
4143
return (path || '/') + stringifyQuery(query) + hash
4244
}
4345

44-
const trailingSlashRE = /\/$/
4546
export function isSameRoute (a: Route, b: ?Route): boolean {
4647
if (b === START) {
4748
return a === b
@@ -76,7 +77,9 @@ function isObjectEqual (a = {}, b = {}): boolean {
7677

7778
export function isIncludedRoute (current: Route, target: Route): boolean {
7879
return (
79-
current.path.indexOf(target.path.replace(/\/$/, '')) === 0 &&
80+
current.path.replace(trailingSlashRE, '/').indexOf(
81+
target.path.replace(trailingSlashRE, '/')
82+
) === 0 &&
8083
(!target.hash || current.hash === target.hash) &&
8184
queryIncludes(current.query, target.query)
8285
)

test/unit/specs/route.spec.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,5 +74,16 @@ describe('Route utils', () => {
7474
expect(isIncludedRoute(a, d)).toBe(false)
7575
expect(isIncludedRoute(a, e)).toBe(false)
7676
})
77+
78+
it('trailing slash', () => {
79+
const a = { path: 'user/1' }
80+
const b = { path: 'user/10' }
81+
const c = { path: 'user/10/' }
82+
const d = { path: 'user/1/' }
83+
expect(isIncludedRoute(a, b)).toBe(false)
84+
expect(isIncludedRoute(a, c)).toBe(false)
85+
expect(isIncludedRoute(b, d)).toBe(false)
86+
expect(isIncludedRoute(c, d)).toBe(false)
87+
})
7788
})
7889
})

0 commit comments

Comments
 (0)