Skip to content

Commit

Permalink
feat(mp): navigatePageTo 支持 query
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Aug 25, 2020
1 parent eaa99f8 commit 71b461e
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 5 deletions.
28 changes: 27 additions & 1 deletion src/mp/navigatePageTo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ describe('navigatePageTo', () => {

test('redirect 正常', async () => {
const { navigatePageTo } = await import('./navigatePageTo')
await navigatePageTo('/', true)
await navigatePageTo('/', undefined, true)
expect(navigateTo).not.toBeCalled()
expect(redirectTo).toBeCalled().toBeCalledTimes(1)
})
Expand Down Expand Up @@ -70,4 +70,30 @@ describe('navigatePageTo', () => {
}),
)
})

test('无 query,支持 query', async () => {
const { navigatePageTo } = await import('./navigatePageTo')
await navigatePageTo('/detail', { id: 1 })
expect(navigateTo)
.toBeCalled()
.toBeCalledTimes(1)
.toBeCalledWith(
expect.objectContaining({
url: `/detail?id=1`,
}),
)
})

test('有 query,支持 query', async () => {
const { navigatePageTo } = await import('./navigatePageTo')
await navigatePageTo('/detail?key=2', { id: 1 })
expect(navigateTo)
.toBeCalled()
.toBeCalledTimes(1)
.toBeCalledWith(
expect.objectContaining({
url: `/detail?key=2&id=1`,
}),
)
})
})
15 changes: 13 additions & 2 deletions src/mp/navigatePageTo.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { AnyObject } from '../types'
import { createUrlQueryString, isUrl } from '../utils'
import { ensureInMiniProgram } from './ensureInMiniProgram'
import { getMiniProgramConfig } from './miniProgramConfig'
import { isUrl } from '../utils'

export function navigatePageTo(url: string, redirect = false): Promise<any> {
export function navigatePageTo(
url: string,
query?: AnyObject,
redirect?: boolean,
): Promise<any> {
return ensureInMiniProgram(mp => {
return new Promise((resolve, reject) => {
if (isUrl(url)) {
Expand All @@ -11,6 +16,12 @@ export function navigatePageTo(url: string, redirect = false): Promise<any> {
url = webUrlToMiniProgramUrl(url)
}
}
if (query && typeof query === 'object') {
const queryString = createUrlQueryString(query)
if (queryString) {
url += (url.indexOf('?') > -1 ? '&' : '?') + queryString
}
}
;(redirect
? ((mp.redirectTo as any) as typeof mp.navigateTo)
: mp.navigateTo)({
Expand Down
4 changes: 2 additions & 2 deletions src/mp/redirectPageTo.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { navigatePageTo } from './navigatePageTo'

export function redirectPageTo(url: string): Promise<any> {
return navigatePageTo(url, true)
export function redirectPageTo(url: string, query?: AnyObject): Promise<any> {
return navigatePageTo(url, query, true)
}

0 comments on commit 71b461e

Please sign in to comment.