我正在使用 Vue Instantsearch,我想让 URL 看起来有点悦目,所以我遵循了本指南:https ://www.algolia.com/doc/guides/building-search-ui/going-further/routing -urls/vue/#seo-friendly-urls
但问题是我无法让类别过滤器正常工作。当我使用类别过滤器时,会生成路由并附加到地址栏,但是当我再次访问相同的 URL 时,无论是通过在地址栏上按 enter 还是刷新页面,类别过滤器都会被剥离,只保留查询字符串.
这是我到目前为止所拥有的:
routing: {
router: historyRouter({
createURL({ qsModule, routeState, location }) {
const urlParts = location.href.match(/^(.*?)\/search/);
const baseUrl = `${urlParts ? urlParts[1] : ""}/`;
const queryParameters = {};
if (routeState.query) {
queryParameters.query = encodeURIComponent(routeState.query);
}
if (routeState.categories) {
queryParameters.categories = routeState.categories.map(encodeURIComponent);
}
if (routeState.page !== 1) {
queryParameters.page = routeState.page;
}
const queryString = qsModule.stringify(queryParameters, {
addQueryPrefix: true,
arrayFormat: "repeat",
});
return `${baseUrl}search/${queryString}`;
},
}),
parseURL({ qsModule, location }) {
const pathnameMatches = location.pathname.match(/search\/(.*?)\/?$/);
const { query = "", page, categories = [] } = qsModule.parse(location.search.slice(1));
const all_categories = Array.isArray(categories) ? categories : [categories];
return {
query: decodeURIComponent(query),
page,
category: all_categories.map(decodeURIComponent),
};
},
stateMapping: {
stateToRoute(uiState) {
const indexUiState = uiState["my_index"] || {};
return {
query: indexUiState.query,
categories: indexUiState.refinementList && indexUiState.refinementList.category,
page: indexUiState.page,
};
},
routeToState(routeState) {
const category_list = routeState.category ? routeState.category.split(" ") : [];
return {
my_index: {
query: routeState.query,
page: routeState.page,
refinementList: {
category: category_list,
},
},
};
},
},
},
该功能很好地选择了该类别routeToState
。但是一旦它到达stateToRoute
,该类别就不再存在了。我的索引名称是my_index
.
任何想法我的代码有什么问题?
更新
我弄清楚是什么导致 URL 重置。我<ais-configure>
用来根据用户的当前位置对结果进行排序:
<ais-configure
:distinct="true"
:around-lat-lng.camel="coordinates"
:around-radius.camel="around_radius"
:hits-per-page.camel="10"
/>
默认情况下coordinates
为空:
data() {
return {
coordinates: ""
}
}
但是在创建组件时,我会确定用户的位置并更新coordinates
. 这将触发它重新渲染。因此失去了通过 URL 提供的初始状态:
created() {
this.$getLocation().then((coordinates) => {
this.coordinates = `${coordinates.lat},${coordinates.lng}`;
});
},
我怎样才能让它不那样做?