Programing

Vue-Router를 사용하여 Vue에서 URL 쿼리 매개 변수를 설정하는 방법

c10106 2022. 4. 8. 19:02
반응형

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또한, 라우터가 탐색할 수 있는 경로를 갖도록 매개변수.A 없이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.

페이지를 다시 로드하거나 돔을 새로 고치지 않고history.pushState그 일을 할 수 있다.
구성 요소 또는 다른 곳에 이 방법을 추가하여 다음을 수행하십시오.

addParamsToLocation(params) {
  history.pushState(
    {},
    null,
    this.$route.path +
      '?' +
      Object.keys(params)
        .map(key => {
          return (
            encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
          )
        })
        .join('&')
  )
}

따라서 구성 요소 내 어디에 있든지 전화하십시오.addParamsToLocation({foo: 'bar'})창에 쿼리 매개 변수가 있는 현재 위치를 푸시하십시오.역사 연재

새 기록 항목을 푸시하지 않고 현재 위치에 쿼리 매개 변수를 추가하려면history.replaceState대신에

Vue 2.6.10 및 Nuxt 2.8.1로 시험한다.

이 방법 조심해!
Vue Router는 url이 변경된 것을 모르기 때문에 pushState 이후 url을 반영하지 않는다.

사실 다음과 같이 쿼리를 푸시할 수 있다.this.$router.push({query: {plan: 'private'}})

기준: https://github.com/vuejs/vue-router/issues/1631

일부 매개 변수를 유지하면서 다른 매개 변수를 변경하려는 경우 vue 라우터 쿼리의 상태를 복사하고 다시 사용하지 마십시오.

참조되지 않은 복사본을 만들므로 다음과 같이 하십시오.

  const query = Object.assign({}, this.$route.query);
  query.page = page;
  query.limit = rowsPerPage;
  await this.$router.push({ query });

는 가 당신이 이다. 그리고 Vue Routerga가 있다.NavigationDuplicated오류:

  const query = this.$route.query;
  query.page = page;
  query.limit = rowsPerPage;
  await this.$router.push({ query });

물론 다음과 같은 쿼리 개체를 분해할 수 있지만 페이지에 대한 모든 쿼리 매개 변수를 알아야 하며 그렇지 않으면 결과적으로 탐색할 때 쿼리 매개 변수를 잃을 수 있다.

  const { page, limit, ...otherParams } = this.$route.query;
  await this.$router.push(Object.assign({
    page: page,
    limit: rowsPerPage
  }, otherParams));
);

참고, 위의 예는 다음과 같다.push(), 이것은 와 함께 작동한다.replace()나도 마찬가지야.

부에로터 3.1.6으로 시험한다.

다음은 페이지를 새로 고치지 않고 URL의 쿼리 매개 변수를 업데이트하는 간단한 솔루션입니다.사용 사례에 적합한지 확인하십시오.

const query = { ...this.$route.query, someParam: 'some-value' };
this.$router.replace({ query });
this.$router.push({ query: Object.assign(this.$route.query, { new: 'param' }) })

, 는 내 기존 하고 있어. 그래그래, 그래그래서 나 는 기고 URL에 기고하고 있어. 이미 일주일동안 파라미터를 가지고 있어. lol, original url:http://localhost:3000/somelink?param1=test1계속 시도해 본 결과:

this.$router.push({path: this.$route.path, query: {param2: test2} });

해서 파라메타1 을하는 파라메타1이 .http://localhost:3000/somelink?param2=test2

이 문제를 해결하기 위해 나는 사용했다.fullPath

this.$router.push({path: this.$route.fullPath, query: {param2: test2} });

이제 나는 성공적으로 오래된 매개 변수들위에 params를 추가했고 결과는

http://localhost:3000/somelink?param1=test1&param2=test2

여러 개의 쿼리 매개 변수를 추가하는 경우, 이것이 내게 효과가 있었다(여기서 https://forum.vuejs.org/t/vue-router-programmatically-append-to-querystring/3655/5)).

위의 답변은 Object와 유사하지만 이것을 변이시킬 것이다.원하는 것이 아닌 $route.query … Object.assign을 수행할 때 첫 번째 인수가 {}인지 확인하십시오.

this.$router.push({ query: Object.assign({}, this.$route.query, { newKey: 'newValue' }) });

내 솔루션, 페이지를 새로 고치지 않고 오류 없음Avoided redundant navigation to current location

    this.$router.replace(
      {
        query: Object.assign({ ...this.$route.query }, { newParam: 'value' }),
      },
      () => {}
    )

여러 쿼리 매개 변수를 한 번에 설정/제거하려면 전역 혼합물의 일부로 아래 메서드를 사용하십시오.this 요소에 사항:vue ㅇㅇㅇㅇ:

    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)
    },

나는 보통 이것을 위해 역사 오브젝트를 사용한다.또한 페이지를 다시 로드하지 않는다.

예:

history.pushState({}, '', 
                `/pagepath/path?query=${this.myQueryParam}`);

당신은 또한 브라우저를 사용할 수 있다.window.history.replaceStateAPI. 컴포넌트를 재마운트하지 않고 중복 탐색을 일으키지 않는다.

window.history.replaceState(null, null, '?query=myquery');

자세한 내용은 여기를 참조하십시오.

vue 라우터가 업데이트 시 페이지를 계속 다시 로드하는 경우, 최상의 해결책은

  const url = new URL(window.location);
  url.searchParams.set('q', 'q');
  window.history.pushState({}, '', url);
        

RouterLink 포함

//With RouterLink
<router-link 
  :to="{name:"router-name", prams:{paramName: paramValue}}"
>
Route Text
</router-link>

//With Methods

methods(){
  this.$router.push({name:'route-name', params:{paramName: paramValue}})
}

메서드 포함

methods(){
  this.$router.push({name:'route-name', params:{paramName, paramValue}})
}

참조URL: https://stackoverflow.com/questions/40382388/how-to-set-url-query-params-in-vue-with-vue-router

반응형