2
const route = useRoute()
const router = useRouter()

deep clone route.query and then change the property of new query,it works (url changes)

let newQuery = { ...route.query}
newQuery.keyword = undefined
router.push({
  name: 'search',
  query: newQuery,
})

but if I change property in route.query and then deep clone changed route.query,it cannot work (url not changes)

route.query.keyword = undefined
let newQuery = { ...route.query}
router.push({
 name: 'search',
 query: newQuery,
})

use console.log(newQuery) to check two newQuery, they are totally same. It confuses me. I wonder why that is

1 Answer 1

2

You should not change route.query directly. It is a readonly value and for changing it you should do router.push({ ...route, query: { ...route.query, ...newQuery }})

So the second approach is wrong and you should avoid it.

Sign up to request clarification or add additional context in comments.

4 Comments

Oh, you mean route.query is readonly and immutable, i guess that's why watch can't detect when I change it directly. There is another question, after i change query directly and console.log({...route.query}) I find value is changed, but router.push() don't work.,it means value actually not changed. What's the reason behind such behaviour?
When you change the route.query directly, the value changes but the exact query of the page does not change. But with using router.push(), you go to a new URL with a new query and the route.query should change too. You can test it by setting a watch for route.query like this: router.push({ ...route , query: { ...route.query, ...someQuery } }); watch(() => route.query, (newQuery) => { console.log(newQuery) })
yes, I understand what you mean. But what bothers me now is, alter query before or after deepClone route.query, likeroute.query.keyword = undefined; let newQuery = route.query and let newQuery = {...route.query}; newQuery.keyword = undefined, I console.log(newQuery), find they are totally same, as two common object, only the second newQuery works. Although route.query is readonly and immutable, I get my wanted query object parameter right?
Yes, you can get what you want from route.query and for changing it you should do it with router.push. I hope I could help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.