跨多条路线保持搜索过滤器 vue 3 (comp api)
persist search filters across multiple routes vue 3 (comp api)
我正在尝试在不使用 Vuex 的情况下跨不同路径保留搜索过滤器。我在 vue 3 中使用组合 api。我研究了将 localStorage 与 onBeforeRouteLeave 以及 watchEffect 一起使用。
下面是adding/removing个过滤器的相关代码
const activeFilters = ref([]);
function addFilter() {
activeFilters.value.push({
value: filtered.value,
});
filtered.value = "";
}
function removeFilter(idx) {
activeFilters.value.splice(idx, 1);
}
我尝试了以下方法,但似乎不起作用:
onMounted(() => {
if (localStorage.filters) {
activeFilters.value = JSON.parse(localStorage.filters);
}
});
onBeforeRouteLeave((to, from) => {
localStorage.filters = JSON.stringify(activeFilters.value);
});
编辑:
我做了一些看起来更接近解决方案的更改,但行为不一致。在路由更改时,有时会保留过滤器,有时不会。
const activeFilters = ref(JSON.parse(localStorage.filters) || []);
watch(
() => activeFilters.value,
(settings) => {
localStorage.filters = JSON.stringify(settings);
},
{ deep: true }
);
问题实际上并不在于 localStorage 代码。我忘记了我对 router-view 标签做了一些更改并且忘记删除它们。对于任何需要帮助的人,这里是我最终使用的代码,用于跨多条路线保留搜索过滤器。
const activeFilters = ref([]);
onMounted(() => {
console.log(localStorage.filters);
if (localStorage.filters) {
activeFilters.value = JSON.parse(localStorage.filters);
}
});
watch(
() => activeFilters.value,
(settings) => {
localStorage.filters = JSON.stringify(settings);
},
{ deep: true }
);
我正在尝试在不使用 Vuex 的情况下跨不同路径保留搜索过滤器。我在 vue 3 中使用组合 api。我研究了将 localStorage 与 onBeforeRouteLeave 以及 watchEffect 一起使用。
下面是adding/removing个过滤器的相关代码
const activeFilters = ref([]);
function addFilter() {
activeFilters.value.push({
value: filtered.value,
});
filtered.value = "";
}
function removeFilter(idx) {
activeFilters.value.splice(idx, 1);
}
我尝试了以下方法,但似乎不起作用:
onMounted(() => {
if (localStorage.filters) {
activeFilters.value = JSON.parse(localStorage.filters);
}
});
onBeforeRouteLeave((to, from) => {
localStorage.filters = JSON.stringify(activeFilters.value);
});
编辑:
我做了一些看起来更接近解决方案的更改,但行为不一致。在路由更改时,有时会保留过滤器,有时不会。
const activeFilters = ref(JSON.parse(localStorage.filters) || []);
watch(
() => activeFilters.value,
(settings) => {
localStorage.filters = JSON.stringify(settings);
},
{ deep: true }
);
问题实际上并不在于 localStorage 代码。我忘记了我对 router-view 标签做了一些更改并且忘记删除它们。对于任何需要帮助的人,这里是我最终使用的代码,用于跨多条路线保留搜索过滤器。
const activeFilters = ref([]);
onMounted(() => {
console.log(localStorage.filters);
if (localStorage.filters) {
activeFilters.value = JSON.parse(localStorage.filters);
}
});
watch(
() => activeFilters.value,
(settings) => {
localStorage.filters = JSON.stringify(settings);
},
{ deep: true }
);