是否可以以声明方式将查询值绑定到props?
我希望/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
}
]
});
我正在使用vue-router 2.3.1
答案 0 :(得分:2)
我不了解您当前的方法存在的问题;解决你的用例就好了。
那就是说,你可以试试Object.assign
,就像这样:
export default new Router({
routes: [{
path: "/:foo?bar=:bar",
name: "Foo",
component: FooPage,
props: route => Object.assign({}, route.params, route.query)
}]
})
...您还可以使用object spread尝试更现代的方法(如果您有babel correctly configured)...
route => ({ ...route.params, ...route.query })
答案 1 :(得分:0)
我不知道有任何声明性指令,但是我喜欢Ricardos general approach。可能存在的问题是,它无条件地将所有查询参数绑定为一个属性,因此只需将其添加到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 };
}
}