Reputation: 8072
In my authority system I store secret token in Vue fields and get it from localStorage in created event:
const app = new Vue({
router: router,
data: {
token: '',
user: null,
},
created: function () {
var token = localStorage.getItem('token');
if (token) {
this.token = token;
}
...
Then I'm trying to fetch token in beforeRouteEnter
method of compomnent:
beforeRouteEnter: function (to, from, next) {
var id = to.params.id;
console.log(router.app.$root.token);
},
But the field is empty, however it defined later. How to correct structure of my application to send api requests with token?
Upvotes: 0
Views: 121
Reputation: 55634
You can pass a callback to next
, which will have access to the instance of the Vue component being routed to.
From the documentation:
The callback will be called when the navigation is confirmed, and the component instance will be passed to the callback as the argument
In your case, it would look like this:
beforeRouteEnter: function (to, from, next) {
var id = to.params.id;
next((vm) => {
console.log(vm.$root.token);
})
},
Now, is this the correct structure for your application to send api requests with this token? That's hard to say without more context and probably too broad. But I'd think you could store the token in whatever library you're using for api requests and that'd be better than referencing it each time the route changes.
Upvotes: 1