To bypass the watchers altogether, you can use watchEffect instead of watch. watchEffect will automatically run the function when any reactive property it depends on changes. You can also use a ref to keep track of whether the filters have been cleared or not. Here's an example:
<script setup>
import { ref, watchEffect } from 'vue'
const search = ref(props.filters.search || '')
const county = ref(props.filters.county || '')
const school = ref(props.filters.school || '')
const areas = ref(props.filters.areas || [])
const filtersCleared = ref(false)
watchEffect(() => {
if (!filtersCleared.value) {
router.get(route('project.search-advanced', {
search: search.value,
county: county.value,
school: school.value,
areas: areas.value,
preserveState: true,
replace: true
}))
}
})
const clearFilters = () => {
filtersCleared.value = true
search.value = ''
county.value = ''
school.value = ''
areas.value.length = 0
filtersCleared.value = false
}
</script>
In this example, we use watchEffect to automatically trigger the router.get function whenever any of the reactive properties change. We also use a ref called filtersCleared to keep track of whether the filters have been cleared or not. When the clearFilters function is called, we set filtersCleared to true, clear the filter values, and then set filtersCleared back to false. This ensures that the watchEffect function doesn't trigger while the filters are being cleared.