Skip to content

Commit 6b7c8b6

Browse files
committed
add support for setting query from URL param
1 parent 2e53603 commit 6b7c8b6

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

components/SearchBox.vue

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,16 @@ export default {
8787
flexsearchSvc.buildIndex(this.$site.pages)
8888
this.placeholder = this.$site.themeConfig.searchPlaceholder || ''
8989
document.addEventListener('keydown', this.onHotkey)
90+
91+
// set query from URL
92+
const params = this.urlParams()
93+
if (params) {
94+
const query = params.get('query')
95+
if (query) {
96+
this.query = decodeURI(query)
97+
this.focused = true
98+
}
99+
}
90100
},
91101
beforeDestroy() {
92102
document.removeEventListener('keydown', this.onHotkey)
@@ -173,6 +183,16 @@ export default {
173183
this.$router.push(this.suggestions[i].path + this.suggestions[i].slug)
174184
this.query = ''
175185
this.focusIndex = 0
186+
this.focused = false
187+
188+
// reset query param
189+
const params = this.urlParams()
190+
if (params) {
191+
params.delete('query')
192+
const paramsString = params.toString()
193+
const newState = window.location.pathname + (paramsString ? `?${paramsString}` : '')
194+
history.pushState(null, '', newState);
195+
}
176196
}
177197
},
178198
focus(i) {
@@ -181,6 +201,12 @@ export default {
181201
unfocus() {
182202
this.focusIndex = -1
183203
},
204+
urlParams() {
205+
if (!window.location.search) {
206+
return null
207+
}
208+
return new URLSearchParams(window.location.search)
209+
}
184210
},
185211
}
186212
</script>

0 commit comments

Comments
 (0)