How do I pass parameters with router.push in vue.js? - vue.js

I'm working on a vue.js application. I'm trying to pass parameters in a redirect from one component to another like this:
this.$router.push({
path: '/my-path',
query: {
anArray: [...]
}
});
Once the component at my-path loads, I'm able to retrieve the parameters like this:
const theArray = this.$route.query.anArray;
The problem is that as soon as I refresh the page, the parameters are gone. When I open Chrome DevTools and put a break point where I retrieve the array from $route.query, I see this:
0: "[object Object]"
1: "[object Object]"
2: "[object Object]"
It seems obvious that it's getting this from the url which is:
http://localhost:8080/my-path?anArray=%5Bobject%20Object%5D&anArray=%5Bobject%20Object%5D&anArray=%5Bobject%20Object%5D
It doesn't seem to realize the 'object' terms in the url are just encodings of actual objects, which are available from $route.query the first time it loads.
Is there another way to pass parameters to a component using $router.push() such that the parameters persist on the page even after refreshing?
I could just try:
this.$router.push('/my-path?anArray=[...]');
...but my goal is to hide the parameters from the user (so don't show them in the url). This is another reason I'm looking for an alternate way of passing parameters (it doesn't even hide them).
I also tried:
this.$router.push({
path: '/my-path',
params: {
anArray: [...]
}
});
...but this made the parameters unavailable in the component (I wonder if this has anything to do with our global router which routes '/my-path' to the MyPath component without specifying parameters; is it wiping out the parameters?).
Thanks.

If you want to hide the parameters from the user, you must not use query. Instead, you should use parameters. Here I let you an example:
//routes.js
path: '/:data',
name: 'Home',
component: () => import('pages/YourPage.vue')
//Passing parameters
this.$router.push({
name: 'Home',
params: { data: yourData}
});
//Receiving parameters in Home component
created() {
console.log('Params: ', this.$route.params);
}
I hope this could be usefull

While params suggested #elC0mpa is a correct answer here are some alternatives depending on the use case:
localStorage/SessionStorage
Save the paramters into localStorage/SessionStorage and retrieve them in the loading sequence of your destination-page as #nachodd pointed out.
⚠ It should be noted that only key value pairs in form of strings are being saved into these storages.
You will need something along the line of
localStorage.setItem(itemKey,JSON.stringify(itemValue)
to set the values and
const itemValue = JSON.parse(localStorage.getItem('itemKey')
to recive it. Also localStorage.removeItem('itemKey') for cleanup.
vuex store
You may want to consider saving your data in the store all together and access it from any vue-component.
The commands needed are this.$store.commit('pathToStore/setterForKey',value) to save something into the store and this.$store.getters[pathToStore/getterForKey'] to receive the items value.
⚠ It should be noted that you need to set up the store accordingly with every state setter/mutation, getter and action. See this documentation.

Related

vue-router : why watch on $route trigger when previous queries rewrite with same values

i have a button in my project when i click on it two queries added to URL
onClickBtn(){
this.$router.push({queries: {name:'kevin' , age:21} })
}
and I have a watch on $route
watch:{
$route:function(){
// call API
}
}
and when i click on that button severall time
watch calls my API every time although nothing has changed
and this make a problem form me
because nothing has changed in route But API is called and the same data is
received .
what should I do to avoid calling API in watch , when queries don't changed ??
The object you are pushing on the router is always different, that's why the $route watch is launched.
You can compare the data you receive in the watch, so that when they are different then you invoke the API:
watch:{
'$route' (newRoute, lastRoute){
// Check if query is different
// call API
}
}
On top of the answer that Cristian provided, you could also even double-check if your stuff has changed before even pushing a new object to your router.
Like this
checkIfUpdateNeeded && this.$router.push({queries: {name: 'kevin', age:21 } })
That way, you will have less moving parts and you won't have a trigger in the watcher for "nothing", especially if you're pushing a bigger object and want to make a deep-diff between 2 objects.

Vuetify router not working when called from JavaScript?

I am trying to navigate the router from methods in Vuetify, but when putting a /path on the go() function, the whole page just refreshes, and navigates nowhere.
Works:
<v-btn router to="/somepage">Goto page</v-btn>
Doesnt work (page just refreshes):
this.$router.go('/somepage')
Works (history go one step back):
this.$router.go(-1)
Browsing the $router object in the Chrome console, it looks just fine. What am I doing wrong?
Vue router provides several functions for programmatic navigation.
this.$router.go(n)
The go(n) function expects n to be a number and is the number of steps forward or backward in the history to travel. I think this is the reason you're not getting the result you expect.
this.$router.push(path|route)
If you'd like to supply an actual path to the function, you should use push() instead of go(). For example to go to the "home" page you might use this.$router.push('/') or to go to the profile page this.$router.push('/profile'). Importantly, when you use push() the path you submit gets added onto the history stack.
this.$router.replace(path|route)
If you do NOT want to add an entry to the history stack, you should use replace() instead of push(). Otherwise, the usage of replace() is the same as push(), i.e. this.$router.replace('/') or this.$router.replace('/profile').
Using a path vs using a route object
When navigating with push(path|route) and replace(path|route) you have the option to use a path, which is just a string that is the URL of the place you want to go, or using a route object. The route object gives you a lot more control and allows you to send route or query parameters to the destination component.
For example, if you want to navigate to the profile page for the user with an id of 3, you could do something like this.$router.push({ path: '/profile', params: { id: 3 } }). Alternatively, if you're using a named route, you could substitute the route name for the path, i.e. this.$router.push({ name: 'profile', params: { id: 3 } }). The name should correspond to the name assigned to the route wherever you've set up your main Router instance.
Using Vuetify's v-btn component
If you're using a Vuetify button component there is NOT a router attribute. Instead you'd just specify the to attribute and Vuetify should automatically interpret it as if it were a router-link, e.g. <v-btn to="/profile">My Profile</v-btn>. Alternatively, you can use a route object, e.g. <v-btn :to="{ path: '/profile', params: { id: 3 } }">Profile</v-btn>. Importantly, notice the colon (:) preceding the to in the second case. This tells Vue to interpret the attribute value as JavaScript instead of plain text.

Vue - same mutation refreshes (or not!) components depending on which component it is called from?

I have problem understanding why THE SAME mutation fails to refresh data displayed in components (although it does change underlying vuex store data!) if it is called from one of the components, but it does refresh the data if called from another component?
I am updating Filter objects stored in store this way: state.report.filters[], where filters is array of Filter objects.
const state = {
report: {
filters: [], // array of Filter objects
...
}
}
My mutation looks for a filter in the array and substitutes the whole Filter object.
const mutations = {
setFilter: (state, newFilterValue) => {
let changedFilter = state.report.filters.find(filter => {
return filter.fieldName === newFilterValue.fieldName;
});
changedFilter = newFilterValue;
}
}
The mutation is called from a method of Filter class defined like this (separate module):
import { store } from './store';
export class Filter {
constructor ({
...
} = {}) {
this.operators = []; // Array of Operator objects
this.value = []; // Array of values - in this case Dates
};
updateOperator (operatorName) { // this mutation refreshes components when executed
this.operator[0] = new Operator(operatorName);
store.commit('setFilter', this); // whole object passed to the mutation
};
updateValue (newValue) { // this mutation changes store value, but fails to refresh components
this.value[0] = newValue; // newValue is a Date
store.commit('setFilter', this);
};
};
The app displays data in rows (each Filter has a separate row), each row contains cells, of which one contains components dedicated to Filter's value and Operator. These dedicated components receive as props callback functions which are methods of the Filter object. They execute the callback functions when a new value is entered passing the value to the Filter which then updates a relevant property and calls the mutation passing in both cases the whole Filter object as payload.
// TABLE CELL COMPONENT displaying filter value and operator
<template>
<td>
<operator-component
:iconName="proppedFilterObject.operator.iconName"
:callback="proppedFilterObject.updateOperator.bind(proppedFilterObject)"
></operator-component>
<value-component
:date="proppedFilterObject.value[0]"
:callback="proppedFilterObject.updateValue.bind(proppedFilterObject)"
></value-component>
</td>
</template>
<script>
export default {
props: ['proppedFilterObject'] // whole filter object
};
</script>
// OPERATOR COMPONENT
<template>
<div #click.stop="chooseOperator">
{{ iconName }} // some operator value display
</div>
</template>
<script>
export default {
methods: {
chooseOperator () {
const modal = new ChooseOperatorModal({
callback: this.callback // this displays another modal for receiving data. The modal calls the callback.
});
},
},
props: ['callback', 'iconName']
};
</script>
// VALUE COMPONENT
<template>
<date-picker v-model="computedDate"> // THIRD PARTY COMPONENT
</date-picker>
{{ date }} // additional display to verify if there's a problem within 'date-picker'
</template>
<script>
import DatePicker from 'vue2-datepicker'; // THIRD PARTY COMPONENT
export default {
components: { DatePicker },
computed: {
computedDate: {
get: function () {
return this.date;
},
set: function (newValue) {
this.callback(newValue);
}
}
},
props: ['callback', 'date']
};
</script>
So, if eg. I enter new operator value from Operator component, everything refreshes. When I enter a new value in the value component, the mutation is executed and store value changed, but displayed data are not refreshed. However, if afterwards I change an operator all the components will refresh and value will get displayed. Even if I change operator in a different Filter object(!). Ie:
a) Change in report.filters[0].value - display not refreshed, but...
b) then change report.filters[1].operator - both report.filters[1].operator AND PREVIOUSLY CHANGED report.filters[0].value get refreshed(?!).
What can be a reason of such behaviour? Where to look for the problem?
Some additional remarks:
1) I am using a third party component "vue2-date-picker" for date choice and display. However it does not seem to be responsible for the problem, as if I try to display the new value just in {{ }} notation it behaves the same way. I have used the date picker in other components and there it functions correctly as well.
2) In the code samples I left out most imports/exports and other seemingly irrelevant elements to keep the question reasonably short.
There are a lot of problems with the code and several of them are contributing to the problems you're seeing. A full, thorough answer that addresses all of these problems would be ridiculously long so instead I will skim through them without going into huge amounts of detail. You will need to do some further reading and experimentation to understand each of these topics properly.
Let's start with this line in the mutation:
changedFilter = newFilterValue;
This line assigns a new value to the local variable changedFilter. That's all. As it's the last line of the mutation the net result is that it doesn't really do anything.
Presumably your intent was to update the array state.report.filters, replacing the old entry with a new entry. However, just updating a local variable isn't going to do that.
At this point you may be wondering 'If that doesn't do anything, then why is the state in my store changing?'. I'll come to that in a moment but first let me prove to you that your existing code does nothing.
Try removing the code inside setFilter completely. Just leave an empty function. Then try clicking around in the UI just like you did before. You'll find that the store state updates just the same as it did before, even though you've removed the code to update the array.
The correct way to implement that mutation would be to use findIndex to find the relevant index and then use either Vue.set or the array's splice method to update the array accordingly. That will change the item in the array. However...
This brings us back to the earlier question. Why is the state updating if the mutation does nothing?
This is because you're using the same object in multiple places. The Filter object held in the array is the same object that your UI is editing. There are no copies being taken, there is just a single object. So when you change the properties of that object inside updateOperator or updateValue this will immediately be reflected inside the store. Calling the setFilter mutation is just asking the store to replace an object with itself.
There's nothing specific to Vue about this. This is just the standard behaviour of reference types in JavaScript. It is also common with many other programming languages that don't directly expose pointers. It can be useful to learn a little about how pointers work in other languages as it will give you a better initial mental model before attempting to understand how reference types behave in JavaScript. Understanding the difference between 'by value' and 'by reference' may also be a useful starting point.
The next topic to cover is reactivity, which very much is a Vue topic.
Specifically, there are certain changes that Vue can't detect. These are usually referred to as the reactivity caveats. You can find more about them in the official documentation:
https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats
https://v2.vuejs.org/v2/guide/list.html#Caveats
There are at least two lines in your code that violate these rules:
this.operator[0] = new Operator(operatorName);
and
this.value[0] = newValue;
You can't set array entries directly by index. The array will update but it won't trigger any reactive dependencies within Vue. Instead you need to use either Vue.set or one of the array methods, e.g. push, pop, splice, etc.. In this example you could use splice.
e.g. Using Vue.set:
Vue.set(this.value, 0, newValue);
e.g. Using splice:
this.value.splice(0, 0, newValue);
Why does all of this matters?
Well Vue will only re-render a component if its reactive dependencies have changed. They are very similar to computed properties in that regard. Here's how it works...
Vue compiles the template down to a function. That function is referred to as the render function. When rendering a component Vue calls the render function and that function returns a description of how to render the component. Any reactive properties that are touched while that function is running will be recorded as dependencies. If, at some point in the future, the value of one of those reactive properties changes then Vue will rerun the render function to generate a new rendering of that component.
There are two key points to take out of this description:
If you fall foul of one of the reactivity caveats then Vue won't know the dependency has changed, so it won't re-render the component.
The render function runs as a whole. It doesn't just target a small chunk of the template, it always runs the whole thing.
So if you change a dependency in a non-reactive way (i.e. one of the caveats) it won't trigger a rendering update. But if you subsequently update a dependency properly, Vue will detect that and will rerun the render function. When it runs it will run the whole thing, so any new values will be picked up, even if they weren't detected when they changed.
It isn't immediately clear to me which rendering dependency is causing your component to re-render. However, it only needs one of them to change in a detectable manner. Any other changes will then get pulled in incidentally when the render function runs and reads their current values.
That covers why your code isn't working. However, I would also worry about your decision to introduce a Filter class. I understand how that may be appealing if you've come from some other OO environment but it isn't typically how Vue is used. It is possible to make it work but you will need a good understanding of both JavaScript reference types and the Vue reactivity system to avoid falling through the cracks. There is no reason why using a specific class to hold your data can't be made to work but in practice it usually ends up being less maintainable than not using such a class. A more typical Vue approach would be to use simple, anonymous objects/arrays to hold the data and then for the data owner (either a component or store module) to be responsible for making any mutations to that data. Events are used to pass changes up the component hierarchy rather than callback props.
Ultimately you will need to judge whether the Filter class is justified but it is probably not what future maintainers of your code will be expecting.

Watch for URL query parameter in Vuex store

I am using Nuxt.js with Vuex and I would like to trigger a mutation when somebody enters in my web with a certain parameter (ex: https://example.com/?param=abc), and pass the parameter to a state.
I tried to check the documentation of the watchQuery property https://nuxtjs.org/api/pages-watchquery, but there’s no examples about how to do this, I just found this How to watch on Route changes with Nuxt and asyncData but I can’t see any way of how to write an action in Vuex store with watchQuery.
I tried writing:
actions: {
watchQuery: true,
asyncData ({ query, app }) {
const { start } = query
const queryString = start ? `?start=${start}` : ''
return app.$axios.$get(`apps/${queryString}`)
.then(res => {
commit('setParam',res.data);
})
},
}
But that syntax is not allowed.
Any help would be welcome, thanks in advance!
From my understanding watchQuery sets a watcher for query string, meaning it's waiting for the query to change while the page is already rendered making it possible to call methods like asyncData() again.
Since you only want to save a certain parameter when the user enters the page and then pass the paramater to a state you just need to move your asyncData method to a page from which you want to get the parameter, you will also need to extract store and query from the context automatically passed into asyncData and then using the store and query save the query parameter into your state.
Here is a simple demonstrantion
// Your page from which you want to save the param
export default {
asyncData({store, query}) { // here we extract the store and query
store.state.somethingForSavingTheParam = query.nameOfTheParamYouWantToSave
// instead of using store.state you could use store.commit(...) if that's what you want
}
}

Express: pass variable to main layout

I'm starting to learn Express and I'm stuck trying to pass a variable in my default layout, that gets loaded every time I render a view, so I don't have to pass it every time I res.render something, like below:
router.get('/', function(req, res, next) {
res.render('home', { title: 'title1', 'isuser':req.user});
});
router.get('/loggedin',function(req,res){
res.render('loggedin', {title: 'title2', 'isuser':req.user});
});
router.get('/register', isLoggedIn, function(req,res)
{
res.render('register', {title: 'title3', 'isuser':req.user});
});
I don't want to pass isuser every time I render, that's why I want to just pass it to my main layout so the information is used automatically.
The default layout isn't explicitly rendered in code (with res.render) but acts like a frame for all rendered views and gets loaded automatically. In my case I use handlebars and I load the default layout like so, in my main app.js:
app.engine('handlebars', expbhs({defaultLayout:'defaultLayout'}));
In Node, you can simply create endpoints server-side, like this:
app.get('login/', function(request, response){
response.render('loginpage', { any data you need });
});
app.get('logout/', function(request, response){
response.render('logoutpage', { any data you need });
});
loginpage and logoutpage are in your views folder and can be jade, handlebars, or any other template. The data to be filled in can be passed as shown above, possibly extracted from the request.
In your HTML you can simply link to your 'login' page (not '/login'), and this should then return your login page.
I realize this question is a couple years old, but I had the exact same question. I think the OP is using express-handlebars (given the "expbhs" abbreviation), so this documentation should be relevant: https://www.npmjs.com/package/express-handlebars#helpers
When you create your instance of express-handlebars, you can pass it some parameters such as defaultLayout and a list of helper functions to generate the data you want to insert into your template.
In my case, I was trying to display the current year in the main template's footer (which appears on every page). Like OP, I did not want to pass this data into every single route.
var handlebars = require('express-handlebars').create({
defaultLayout:'main',
helpers: {
year: function() {
return new Date().getFullYear();
}
}
});
This results in displaying the year where I've written {{year}} in main.handlebars. Hope this helps someone else.