programing

vue-roouter를 사용하여 소품에 쿼리 바인딩

prostudy 2022. 3. 7. 22:10
반응형

vue-roouter를 사용하여 소품에 쿼리 바인딩

질의 값을 선언적으로 소품에 바인딩할 수 있는가?

나는 되고 싶다./my-foo?bar=my-bar소품을 건네다{foo: "my-foo", bar: "my-bar"}.

나는 현재 이런 것을 사용하고 있다.

export default new Router({
  routes: [
    {
      path: "/:foo",
      name: "Foo",
      component: FooPage,
      props: route => ({ foo: route.params.foo, bar: route.query.bar})
    }
  ]
});

그리고 나는 다음과 같은 것을 찾고 있다.

export default new Router({
  routes: [
    {
      path: "/:foo?bar=:bar",
      name: "Foo",
      component: FooPage,
      props: true
    }
  ]
});

나는 2.3.1 vue-roouter를 사용하고 있다.

현재 접근 방식의 문제를 이해할 수 없다. 사용 사례를 잘 해결하십시오.

즉, 다음과 같은 것을 시도해 볼 수 있다.

export default new Router({
  routes: [{
    path: "/:foo?bar=:bar",
    name: "Foo",
    component: FooPage,
    props: route => Object.assign({}, route.query, route.params)
  }]
})

... 또한 물체 스프레드를 사용하여 보다 현대적인 접근법을 시도할 수 있다(바벨이 올바르게 구성된 경우) ...

route => ({ ...route.query, ...route.params })

하고 있다route.params경로 매개 변수를 재정의하는 쿼리 스트링을 방지하는 마지막 병합/연결 항목.

나는 그것에 대한 어떤 선언적인 지시도 알지 못하지만, 리카르도스의 일반적인 접근법을 좋아한다.문제가 될 수 있는 것은 모든 조회 파라미터를 무조건 소품으로 묶어서 URL에 추가하는 것만으로 해당 구성요소의 미리 정의된 소품들을 수정할 수 있다는 점이다.

필터를 사용하고도 재사용 가능 여부를 확인하려면 도우미 함수를 정의하고 보다 상세하게 쿼리를 바인딩하십시오.

import bindQuery from "./router-query-bind";

export default new Router({
    routes: [{
        name: "Foo",
        path: "/:foo",
        props: bindQuery(["bar"]), // only binds 'bar' from query as a prop
        component: FooPage
    }, {
        name: "Bar",
        path: "/:bar",
        props: bindQuery(), // binds all query parameters as a props
        component: BarPage
    }]
});

다음과 같은 구현을 통해.이것은 TypeScript이며 유형 주석이 있다는 점에 유의하십시오.일반 JavaScript가 필요하면 제거하십시오.

import { Route } from "vue-router";
type RoutePropsFunction = (route: Route) => Object;

/**
 * Creates a props-function for Vue-Router to pass all route parameters and query parameters as
 * props to the routed component.
 * You may filter the passed query parameters by name so that only the expected
 * props will be bound.
 * @param queryFilter List of query parameters which will be passed as props to the component.
 * This is optional. If not set all query parameters will be bound.
 */
export default function (queryFilter?: string[]): RoutePropsFunction {
    return function (route: Route) {
        const filtered = queryFilter ?
            queryFilter.reduce((a, b) => ({ ...a, [b]: route.query[b] }), {}) :
            route.query;
        return { ...route.params, ...filtered };
    }
}

참조URL: https://stackoverflow.com/questions/44783787/bind-query-to-props-with-vue-router

반응형