I'm trying to persist search filters across different routes without the use of Vuex. I'm using the composition api in vue 3. I looked into using localStorage with onBeforeRouteLeave and also watchEffect.
Below is the relevant code for adding/removing filters
const activeFilters = ref([]);
function addFilter() {
activeFilters.value.push({
value: filtered.value,
});
filtered.value = "";
}
function removeFilter(idx) {
activeFilters.value.splice(idx, 1);
}
I tried the following, but doesn't seem to work:
onMounted(() => {
if (localStorage.filters) {
activeFilters.value = JSON.parse(localStorage.filters);
}
});
onBeforeRouteLeave((to, from) => {
localStorage.filters = JSON.stringify(activeFilters.value);
});
Edit:
I've made some changes that looks like it gets me closer to the solution, but the behavior is inconsistent. On the route change, sometimes the filter is persisted, sometimes it's not.
const activeFilters = ref(JSON.parse(localStorage.filters) || []);
watch(
() => activeFilters.value,
(settings) => {
localStorage.filters = JSON.stringify(settings);
},
{ deep: true }
);