Vue-Router를 사용하여 Vue에서 URL 쿼리 매개 변수를 설정하는 방법
입력 필드를 변경할 때 Vue-router를 사용 하여 쿼리 매개 변수를 설정하려고합니다. 다른 페이지로 이동하고 싶지 않지만 같은 페이지에서 URL 쿼리 매개 변수를 수정하고 싶습니다.
this.$router.replace({ query: { q1: "q1" } })
그러나 이것은 또한 페이지를 새로 고침하고 y 위치를 0으로 설정합니다. 즉, 페이지 상단으로 스크롤됩니다. 이것이 URL 쿼리 매개 변수를 설정하는 올바른 방법입니까 아니면 더 나은 방법이 있습니까?
편집 :
내 라우터 코드는 다음과 같습니다.
export default new Router({
mode: 'history',
scrollBehavior: (to, from, savedPosition) => {
if (to.hash) {
return {selector: to.hash}
} else {
return {x: 0, y: 0}
}
},
routes: [
.......
{ path: '/user/:id', component: UserView },
]
})
다음은 문서의 예입니다.
// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
참조 : https://router.vuejs.org/en/essentials/navigation.html
해당 문서에서 언급했듯이 다음 router.replace과 같이 작동합니다.router.push
따라서 문제의 샘플 코드에 올바르게 포함되어있는 것 같습니다. 그러나 라우터가 탐색 할 경로를 갖도록 name또는 path매개 변수도 포함해야 할 수도 있습니다 . 없이 name또는 path, 그것은 매우 의미있는 보이지 않는다.
이것이 현재 나의 이해입니다.
query라우터의 경우 선택 사항입니다. 뷰를 구성하는 구성 요소에 대한 몇 가지 추가 정보name또는path필수-에 표시 할 구성 요소를 결정합니다<router-view>.
샘플 코드에서 누락 된 것일 수 있습니다.
편집 : 주석 후 추가 세부 정보
이 경우 명명 된 경로 를 사용해 보셨습니까 ? 동적 경로가 있으며 매개 변수와 쿼리를 별도로 제공하는 것이 더 쉽습니다.
routes: [
{ name: 'user-view', path: '/user/:id', component: UserView },
// other routes
]
그리고 당신의 방법에서 :
this.$router.replace({ name: "user-view", params: {id:"123"}, query: {q1: "q1"} })
기술적으로 위와 사이에는 차이가 없지만 this.$router.replace({path: "/user/123", query:{q1: "q1"}})경로 문자열을 구성하는 것보다 명명 된 경로에 동적 매개 변수를 제공하는 것이 더 쉽습니다. 그러나 두 경우 모두 쿼리 매개 변수를 고려해야합니다. 두 경우 모두 쿼리 매개 변수가 처리되는 방식에서 잘못된 점을 찾을 수 없습니다.
경로 내부에있는 후에는 동적 매개 변수를로 가져오고 this.$route.params.id쿼리 매개 변수를 this.$route.query.q1.
실제로 다음과 같이 쿼리를 푸시 할 수 있습니다. this.$router.push({query: {plan: 'private'}})
기반 : https://github.com/vuejs/vue-router/issues/1631
페이지를 다시로드 하거나 DOM을 새로 고치지 않고도history.pushState 작업을 수행 할 수 있습니다.
구성 요소 또는 다른 곳에이 메서드를 추가하여 수행합니다.
addParamsToLocation(params) {
history.pushState(
{},
null,
this.$route.path +
'?' +
Object.keys(params)
.map(key => {
return (
encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
)
})
.join('&')
)
}
So anywhere in your component, call addParamsToLocation({foo: 'bar'}) to push the current location with query params in the window.history stack.
To add query params to current location without pushing a new history entry, use history.replaceState instead.
Tested with Vue 2.6.10 and Nuxt 2.8.1.
Be careful with this method!
Vue Router don't know that url has changed, so it doesn't reflect url after pushState.
this.$router.push({ query: Object.assign(this.$route.query, { new: 'param' }) })
To set/remove multiple query params at once I've ended up with the methods below as part of my global mixins (this points to vue component):
setQuery(query){
let obj = Object.assign({}, this.$route.query);
Object.keys(query).forEach(key => {
let value = query[key];
if(value){
obj[key] = value
} else {
delete obj[key]
}
})
this.$router.replace({
...this.$router.currentRoute,
query: obj
})
},
removeQuery(queryNameArray){
let obj = {}
queryNameArray.forEach(key => {
obj[key] = null
})
this.setQuery(obj)
},
참고URL : https://stackoverflow.com/questions/40382388/how-to-set-url-query-params-in-vue-with-vue-router
'IT박스' 카테고리의 다른 글
| JSON을 편집하는 Emacs 모드 (0) | 2020.10.22 |
|---|---|
| iOS 7 UIRefreshControl tintColor가 beginRefreshing에서 작동하지 않습니다. (0) | 2020.10.22 |
| keras에서 두 레이어를 연결하는 방법은 무엇입니까? (0) | 2020.10.22 |
| % d가 정수를 나타내는 이유는 무엇입니까? (0) | 2020.10.22 |
| iPhone Simulator에 자체 서명 된 인증서를 추가 하시겠습니까? (0) | 2020.10.21 |