How to set URL query params in Vue with Vue-Router - javascript
I am trying to set query params with Vue-router when changing input fields, I don't want to navigate to some other page but just want to modify url query params on the same page, I am doing like this:
this.$router.replace({ query: { q1: "q1" } })
But this also refreshes the page and sets the y position to 0, ie scrolls to the top of the page. Is this the correct way to set the URL query params or is there a better way to do it.
Edited:
Here is my router code:
export default new Router({
mode: 'history',
scrollBehavior: (to, from, savedPosition) => {
if (to.hash) {
return {selector: to.hash}
} else {
return {x: 0, y: 0}
}
},
routes: [
.......
{ path: '/user/:id', component: UserView },
]
})
Here is the example in docs:
// with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
Ref: https://router.vuejs.org/en/essentials/navigation.html
As mentioned in those docs, router.replace works like router.push
So, you seem to have it right in your sample code in question. But I think you may need to include either name or path parameter also, so that the router has some route to navigate to. Without a name or path, it does not look very meaningful.
This is my current understanding now:
query is optional for router - some additional info for the component to construct the view
name or path is mandatory - it decides what component to show in your <router-view>.
That might be the missing thing in your sample code.
EDIT: Additional details after comments
Have you tried using named routes in this case? You have dynamic routes, and it is easier to provide params and query separately:
routes: [
{ name: 'user-view', path: '/user/:id', component: UserView },
// other routes
]
and then in your methods:
this.$router.replace({ name: "user-view", params: {id:"123"}, query: {q1: "q1"} })
Technically there is no difference between the above and this.$router.replace({path: "/user/123", query:{q1: "q1"}}), but it is easier to supply dynamic params on named routes than composing the route string. But in either cases, query params should be taken into account. In either case, I couldn't find anything wrong with the way query params are handled.
After you are inside the route, you can fetch your dynamic params as this.$route.params.id and your query params as this.$route.query.q1.
Without reloading the page or refreshing the dom, history.pushState can do the job.
Add this method in your component or elsewhere to do that:
addParamsToLocation(params) {
history.pushState(
{},
null,
this.$route.path +
'?' +
Object.keys(params)
.map(key => {
return (
encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
)
})
.join('&')
)
}
So anywhere in your component, call addParamsToLocation({foo: 'bar'}) to push the current location with query params in the window.history stack.
To add query params to current location without pushing a new history entry, use history.replaceState instead.
Tested with Vue 2.6.10 and Nuxt 2.8.1.
Be careful with this method!
Vue Router don't know that url has changed, so it doesn't reflect url after pushState.
Actually you can push query like this: this.$router.push({query: {plan: 'private'}})
Based on: https://github.com/vuejs/vue-router/issues/1631
Okay so i've been trying to add a param to my existing url wich already have params for a week now lol,
original url: http://localhost:3000/somelink?param1=test1
i've been trying with:
this.$router.push({path: this.$route.path, query: {param2: test2} });
this code would juste remove param1 and becomes
http://localhost:3000/somelink?param2=test2
to solve this issue i used fullPath
this.$router.push({path: this.$route.fullPath, query: {param2: test2} });
now i successfully added params over old params nd the result is
http://localhost:3000/somelink?param1=test1¶m2=test2
If you are trying to keep some parameters, while changing others, be sure to copy the state of the vue router query and not reuse it.
This works, since you are making an unreferenced copy:
const query = Object.assign({}, this.$route.query);
query.page = page;
query.limit = rowsPerPage;
await this.$router.push({ query });
while below will lead to Vue Router thinking you are reusing the same query and lead to the NavigationDuplicated error:
const query = this.$route.query;
query.page = page;
query.limit = rowsPerPage;
await this.$router.push({ query });
Of course, you could decompose the query object, such as follows, but you'll need to be aware of all the query parameters to your page, otherwise you risk losing them in the resultant navigation.
const { page, limit, ...otherParams } = this.$route.query;
await this.$router.push(Object.assign({
page: page,
limit: rowsPerPage
}, otherParams));
);
Note, while the above example is for push(), this works with replace() too.
Tested with vue-router 3.1.6.
Here's my simple solution to update the query params in the URL without refreshing the page. Make sure it works for your use case.
const query = { ...this.$route.query, someParam: 'some-value' };
this.$router.replace({ query });
My solution, no refreshing the page and no error Avoided redundant navigation to current location
this.$router.replace(
{
query: Object.assign({ ...this.$route.query }, { newParam: 'value' }),
},
() => {}
)
this.$router.push({ query: Object.assign(this.$route.query, { new: 'param' }) })
You could also just use the browser window.history.replaceState API. It doesn't remount any components and doesn't cause redundant navigation.
window.history.replaceState(null, '', '?query=myquery');
More info here.
For adding multiple query params, this is what worked for me (from here https://forum.vuejs.org/t/vue-router-programmatically-append-to-querystring/3655/5).
an answer above was close … though with Object.assign it will mutate this.$route.query which is not what you want to do … make sure the first argument is {} when doing Object.assign
this.$router.push({ query: Object.assign({}, this.$route.query, { newKey: 'newValue' }) });
To set/remove multiple query params at once I've ended up with the methods below as part of my global mixins (this points to vue component):
setQuery(query){
let obj = Object.assign({}, this.$route.query);
Object.keys(query).forEach(key => {
let value = query[key];
if(value){
obj[key] = value
} else {
delete obj[key]
}
})
this.$router.replace({
...this.$router.currentRoute,
query: obj
})
},
removeQuery(queryNameArray){
let obj = {}
queryNameArray.forEach(key => {
obj[key] = null
})
this.setQuery(obj)
},
I normally use the history object for this. It also does not reload the page.
Example:
history.pushState({}, '',
`/pagepath/path?query=${this.myQueryParam}`);
The vue router keeps reloading the page on update, the best solution is
const url = new URL(window.location);
url.searchParams.set('q', 'q');
window.history.pushState({}, '', url);
With RouterLink
//With RouterLink
<router-link
:to="{name:"router-name", prams:{paramName: paramValue}}"
>
Route Text
</router-link>
//With Methods
methods(){
this.$router.push({name:'route-name', params:{paramName: paramValue}})
}
With Methods
methods(){
this.$router.push({name:'route-name', params:{paramName, paramValue}})
}
This is the equivalent using the Composition API
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
router.push({ path: 'register', query: { plan: 'private' }})
</script>
You can also use the Vue devtools just to be sure that it's working as expected (by inspecting the given route you're on) as shown here: https://stackoverflow.com/a/74136917/8816585
Update
That will meanwhile mount/unmount components. Some vanilla JS solution is still the best way to go for that purpose.
Related
Router search not capturing whats in URL
My URL currently looks as following. http://localhost:3000/path/label?default=1111 I want to append additional query string values. Thus after appending, I am expecting it to appear as follows. http://localhost:3000/path/label?name=name&age=100&default=ab07 Current logic works when I look at it in the browser URL. I see this: http://localhost:3000/path/label?name=name&age=100&default=ab07 But when I console print it: console.log(`router: ${JSON.stringify(router.location.search)}`) I end up printing following: router: "?default=1111" It should have printed: router: "?name=name&age=100&default=ab07" Thought maybe the router updates fine, just some delay in print. But that is not the case. Once I have amended the query params. I need to push it to another url with same params. At this stage it is still wrongly only holding the initial query params and ignoring my new params. Why? Expected to push to: newPath/?name=name&age=100&default=ab07 Incorrectly pushing to: newPath?default=ab07 This is how I am appending the query and search params. export const add = (router, data) => { const pathname = router.location.pathname; let updatedQuery = { ...router.location.query, }; if (hasValue) { const details = { name: 'name', 'age': '100' }; updatedQuery = { ...updatedQuery, ...details, }; } router.replace({ pathname, query: updatedQuery, search: new URLSearchParams(updatedQuery), }); } This is how I am pushing it to another path while still wanting to retain the same query params. // This function is in another file. redirectToAnotherPage = (router, data) => { // other logic return `/newPath/${router.location.search}`; } This is how I am calling both above functions. import { withRouter } from 'react-router'; const constructAndRedirect() { // other logic add(router, data) router.push(redirectToAnotherPage(router, data)); }
How to properly use context in tRPC?
Let's say I have a very basic API with two sets of endpoints. One set queries and mutates properties about a User, which requires a username parameter, and one set queries and mutates properties about a Post, which requires a post ID. (Let's ignore authentication for simplicity.) I don't currently see a good way to implement this in a DRY way. What makes the most sense to me is to have a separate Context for each set of routes, like this: // post.ts export async function createContext( opts?: trpcExpress.CreateExpressContextOptions ) { // pass through post id, throw if not present } type Context = trpc.inferAsyncReturnType<typeof createContext>; const router = trpc .router() .query("get", { resolve(req) { // get post from database return post; }, }); // similar thing in user.ts // server.ts const trpcRouter = trpc .router() .merge("post.", postRouter) .merge("user.", userRouter); app.use( "/trpc", trpcExpress.createExpressMiddleware({ router: trpcRouter, createContext, }) ); This complains about context, and I can't find anything in the tRPC docs about passing a separate context to each router when merging. Middleware doesn't seem to solve the problem either - while I can fetch the post/user in a middleware and pass it on, I don't see any way to require a certain type of input in a middleware. I would have to throw { input: z.string() } or { input: z.number() } on every query/mutation, which of course isn't ideal. The docs and examples seem pretty lacking for this (presumably common) use case, so what's the best way forward here?
This functionality has been added in (unreleased as of writing) v10. https://trpc.io/docs/v10/procedures#multiple-input-parsers const roomProcedure = t.procedure.input( z.object({ roomId: z.string(), }), ); const appRouter = t.router({ sendMessage: roomProcedure .input( z.object({ text: z.string(), }), ) .mutation(({ input }) => { // input: { roomId: string; text: string } }), });
NextJS - Appending a query param to a dynamic route
In my NextJS app, I have a language selector that's visible on every page. When I select a new language, I just want to replace the current URL by appending a query param lang=en to it. Here's the function that replaces the URL: const changeLanguage = (lang: LanguageID) => { replace({ pathname, query: { ...query, lang }, }); }; In this example, replace, query and pathname are coming from the next router. Now, everything works for static routes, but I'm unable to make it work for dynamic routes. For example, I have the following folder structure: pages |_customers |__index.tsx |__[customerId].tsx If I'm on http://localhost/customers and I change my language to English, the URL changes to http://localhost/customers?lang=en which is what I want. However, if I'm on http://localhost/customer/1 and I change my language to English, the URL changes to http://localhost/customers/[customerId]?customerId=1&lang=en, instead of the URL I'm expecting http://localhost/customers/1?lang=en. Now, I know that I could use asPath on the router, and reconstruct the query string object by appending lang to it, but I feel that it's something that should be build into Next. Also, I know it could be easily done with vanilla JS, but it's not the point here. Am I missing something? Is there an easier way to append query params to a dynamic route without doing a server-side re-rendering? Thanks
Just add more param to current router then push itself const router = useRouter(); router.query.NEWPARAMS = "VALUE" router.push(router)
The solution which doesn't need to send the whole previous route, as replace just replaces what we need to replace, so query params: const router = useRouter(); router.replace({ query: { ...router.query, key: value }, });
If we want to have this as a link - use it like so: // ... const { query } = useRouter(); // ... <Link href={{ pathname: router.pathname, query: { ...query, lang }, }} passHref shallow replace ></Link>
I tried adding my param to the route query and pushing the router itself, as mentioned here, it works, but I got a lot of warnings: So, I then pushed to / and passed my query params as following: const router = useRouter(); router.push({ href: '/', query: { myQueryParam: value } }); I hope that works for you too.
I ended up using the solution that I wanted to avoid in the first place, which was to play with the asPath value. Atleast, there's no server-side re-rendering being done since the path is the same. Here's my updated changeLanguage function (stringifyUrl is coming from the query-string package) const changeLanguage = (lang: LanguageID) => { const newPathname = stringifyUrl({ url: pathname, query: { ...query, lang } }); const newAsPath = stringifyUrl({ url: asPath, query: { lang } }); replace(newPathname, newAsPath); };
If anyone is still looking the answer ,for Next,js ^11.1.2.I hope this helps you out.Use const router = useRouter(); router.push({ pathname: "/search", query: { key: key } });
An alternative approach when you have dynamic routing in Next.js, and want to do a shallow adjustment of the route to reflect updated query params, is to try: const router = useRouter() const url = { pathname: router.pathname, query: { ...router.query, page: 2 } } router.push(url, undefined, { shallow: true }) This will retreive the current path (router.pathname) and query (router.query) details, and merge them in along with your new page query param. If your forget to merge in the existing query params you might see an error like: The provided href value is missing query values to be interpolated properly
In latest version, Next 13, some of the functionality moved to other hooks, which query and path are some of them. You can use useSearchParams to get query and usePathname instead of pathname. By the time I am writing this answer, it does not have a stable version and you can find the beta documents here: https://beta.nextjs.org/docs/api-reference/use-router
let queryParams; if (typeof window !== "undefined") { // The search property returns the querystring part of a URL, including the question mark (?). queryParams = new URLSearchParams(window.location.search); // quaeryParams object has nice methods // console.log("window.location.search", queryParams); // console.log("query get", queryParams.get("location")); } inside changeLanguage, const changeLanguage = (lang: LanguageID) => { if (queryParams.has("lang")) { queryParams.set("lang", lang); } else { // otherwise append queryParams.append("lang", lang); } router.replace({ search: queryParams.toString(), }); };
Force to use window.location.href in vue-router hash mode
I'm using vue-router 3.0.1, and the mode is hash. The current url is: /#/?type=1 I tried to use window.location.href for the same path, but different query parameter like this. window.location.href = '/#/?type=2'; But the url of the browser changes, but nothing else happens. At the first place, I am trying this, because router.push didn't re-render the component. The original window.location.href should give the different result, but vue-router looks like to override window.location.href. How can I force to move to /#/?type=2, in this case?
You don't need to use window.location.href to make it work. The problem here is that the component is reused when you only update the query parameter and the component will not automatically re-render. One way to solve this issue is to watch the $route in your component. Here's an code example. You also can find the jsFiddle here https://jsfiddle.net/Fourzero/cbnom5sL/22/. Html <script src="https://npmcdn.com/vue/dist/vue.js"></script> <script src="https://npmcdn.com/vue-router/dist/vue-router.js"></script> <div id="app"> <!-- You can use router-link to trigger the url change or router.push in your code -- it doesn't matter. --> <router-link to="/?type=2">type 2</router-link> <router-link to="/?type=1">type 1</router-link> <router-view></router-view> </div> JavaScript const Bar = { template: '<div>Type {{type}}</div>', data () { return { type: '' } }, mounted () { this.type = this.$route.query.type; }, watch: { $route(to, from) { // Update the data type when the route changes. this.type = to.query.type; } } } const router = new VueRouter({ mode: 'hash', routes: [ { path: '', component: Bar }, ] }) new Vue({ router, el: '#app', data: { msg: 'Hello World' } }) For detailed explanation, you can refer the official doc https://router.vuejs.org/guide/essentials/dynamic-matching.html.
How can I add computed state to graph objects in React Apollo?
I really like the graphQL pattern of having components request their own data, but some data properties are expensive to compute and so I want to localize the logic (and code) to do so. function CheaterList({ data: { PlayerList: players } }) { return ( <ul> {players && players.map(({ name, isCheater }) => ( <li key={name}>{name} seems to be a {isCheater ? 'cheater' : 'normal player'}</li> ))} </ul> ); } export default graphql(gql` query GetList { PlayerList { name, isCheater } } `)(CheaterList); The schema looks like: type Queries { PlayerList: [Player] } type Player { name: String, kills: Integer, deaths: Integer } And so I want to add the isCheater property to Player and have its code be: function computeIsCheater(player: Player){ // This is a simplified version of what it actually is for the sake of the example return player.deaths == 0 || (player.kills / player.deaths) > 20; } How would I do that? Another way of phrasing this would be: how do I get the isCheater property to look as though it came from the backend? (However, if an optimistic update were applied the function should rerun on the new data)
Note: Local state management is now baked into apollo-client -- there's no need to add a separate link in order to make use of local resolvers and the #client directive. For an example of mixing local and remote fields, check out of the docs. Original answer follows. As long as you're using Apollo 2.0, this should be possible by utilizing apollo-link-state as outlined in the docs. Modify your client configuration to include apollo-link-state: import { withClientState } from 'apollo-link-state'; const stateLink = withClientState({ cache, //same cache object you pass to the client constructor resolvers: linkStateResolvers, }); const client = new ApolloClient({ cache, link: ApolloLink.from([stateLink, new HttpLink()]), }); Define your client-only resolvers: const linkStateResolvers = { Player: { isCheater: (player, args, ctx) => { return player.deaths == 0 || (player.kills / player.deaths) > 20 } } } Use the #client directive in your query export default graphql(gql` query GetList { PlayerList { name kills deaths isCheater #client } } `)(CheaterList); However, it appears that combining local and remote fields in a single query is currently broken. There's an open issue here that you can track.