I use beforeRouteLeave for open dialog component when calling component with router.
beforeRouteLeave(to, from, next) {
if (to.name === "read-content") {
this.displayProductModal(to);
} else {
next();
}
},
When I call nuxt-link to the read-content (route.name) page a dialog opens. Sometimes I don't want to run the dialog. But I want to access that page directly, what should I do?
I found my answer, i use condition in parameter to -> if(to.hash) add token or fake param after route/# url.
If there is any other better way please suggest me.
:to="{
name: 'read-content',
params: { content: id },
hash: '#x',
}"
Related
In Vue3 is there a way to pass properties to a route without the values showing in the url?
I defined the route like this:
{
path: '/someRoute',
name: 'someRoute',
component: () => import('#/app/pages/SomeRoute.vue'),
props: (route) => {
...route.params
}, // <-- I've seen this method in Vue2 but in Vue3 the route.params is just empty here
}
I call the route like this:
<router-link :to="{ name: 'someRoute', params: { message: 'Some Message' } }">Some link</router-link>
When I change path into path: '/someRoute/:message', the message come through just fine but I just want to pass the message without it showing up in the url.
I've seen a couple of Vue2 examples that use this method (e.g. https://stackoverflow.com/a/50507329/1572330) but apparently they don't work in Vue3 anymore.
Also all the examples in the Vue3 docs (https://github.com/vuejs/vue-router/blob/dev/examples/route-props/app.js / https://v3.router.vuejs.org/guide/essentials/passing-props.html) pass on their values through the url itself so I'm not sure if it's even possible anymore.
Any thoughts on this would be helpfull.
Finally I found something about this in the changelog: https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22
Apparently it's no longer possible to send properties via params without the showing in the url. But fortunately they give some alternative suggestions.
The one that worked best for my situation was to use state: { ... } instead:
<router-link :to="{ name: 'someRoute', force: true, state: { message: 'Some Message' } }">Some link</router-link>
Now in the code of the page I read the property from the history.sate and put the value in whatever property I need it.
In case the url/route itself doesn't change you need to have an update hook and use force: true
public created() {
this.message = window.history.state.message;
}
public updated() {
this.message = window.history.state.message;
}
PS history.state has some limitations so in other situations one of the other suggestions from the changelog might work better
I have two (or more) VueJS routes that contain a router-link pointing to the same third route.
/pages/list
<router-link :to="{name:'add-page'}">Add</router-link>
/pages/other-list
<router-link :to="{name:'add-page'}">Add</router-link>
If I put a put link on the third page with $router.back(), the link will take me back in history to whichever previous page I came from.
However, if enter the add-page route directly into my browser, there is no history. I would like to set a default value for that page, and preferably not rely on a global default.
What is the best way to select a default route if there is no history on a specific component?
Would a Navigation Guard fits your needs?
You would use it something like:
router.beforeEach((to, from, next) => {
if (to.name === 'add-page' && to.) {
//Your logic here
//eg a redirect
next({ name: 'MyBaseRoute' })
} else {
next()
}
})
or if you need just for a selected component you can use the in-component guard:
beforeRouteEnter (to, from, next) {
// called before the route that renders this component is confirmed.
// does NOT have access to `this` component instance,
// because it has not been created yet when this guard is called!
},
Having an issue with my url updating but the page not.
From the home page, I display a list of projects. Clicking a project will take you to "website.com/project/project-1" and everything works as intended.
However, at the bottom of that page, I again show a list. This list is the same as homepage, with same functionality. But the problem is, is that it will update the url to "website.com/project/project-2" but the page will not re-render or change.
An example of my code
My current router-path of the component.
path: '/project/:project_slug',
name: 'ProjectPage',
component: ProjectPage
My Router Link from the project page to the new project page
<router-link :to="{ name: 'ProjectPage', params: {project_slug: projectHighlightSlug} }">
<h4 class="header-17 semibold">{{projectTitle}}</h4>
</router-link>
Update
This is my current method/watch section
methods: {
goToProject() {
this.$router.push({
name: 'ProjectPage',
params: {project_slug: this.projectHighlightSlug}
})
},
},
watch:{
// eslint-disable-next-line no-unused-vars
'$route'(to, from) {
this.goToProject();
}
}
However, the to,from is "defined but never used" and clicking my button to call goToProject() gives me the error;
"You may have an infinite update loop in watcher with expression "$route""
As explained in the Vue Router docs, when the url the user navigates to uses the same component, it uses the same instance of that component. The docs therefore recommend to listen to $route changes or to use the beforeRouteUpdate navigation guard.
You need to watch the routes to update your page. see code below
watch:{
'$route' (to, from) {
this.goToProject()
// call your method here that updates your page
}
},
source dynamic route matching
I m trying to redirect from one URL to another URL using Vue router eg code
{
path: '/verifyemail/:id/:token',
//can i somelogic here when user entered
},
{
path: '/login',
component:login
},
what I m trying to do? when the user registered himself. server send email verification link to his email when a user clicks on verify button from his email then it should first call verifyemail url. where it has an ajax call with a parameter which i m getting from verifyemail url now after the success it should move to login url note:- i don't have any component in my verfiyemail route
is it possible to do this or is there anyother way to achieve this
The route configuration is only data, so there's not really any way to do this exactly as you'd like.
If you create a component to handle the /verifyemail/ route you can just use this.$router.push(redirectToMe) in it. See the Vue Router docs for more information.
Alternatively, this sounds more like something a backend server would handle on it's own, so maybe you don't even need Vue to worry about it.
finally, I arrive with one solution may be this help other
let start, I send the email with verify button which has link something like "localhost:8080/#/verfiyemail/("ACCESSTOKEN")" NOW I my vue part i does something like
in vue-route
path: '/verifyemail/:uid',
beforeEnter:(to, from, next) => {
let uid=to.params.uid;
next({ path: '/', query: { id: uid}})
}
},
{
path: '/',
name: 'Login',
component: Login,
},
and i my login.vue
created(){
this.verfiyemai();
},
methods:{
verfiyemai(){
var _this=this
var submit=0
if(this.$route.query.id!=undefined ){
if(this.$route.query.id.length<=50){
this.$router.push('/');
submit=1;
}
if(submit==0){
this.$http.get('/api/users/confirm?uid='+this.$route.query.id+'')
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
});
}
}
},
}
from email, I redirect the user to verfiyemail with token id as a parameter from verifyemail route, after that I redirect to the login URL passing the parameter as query and in my login vue I had created a method which checks query length if it greater than 50 then it will post axios response to the server
I have a simple use case, where my application is using vue-router and vuex. Then store contains a user object which is null in the beginning. After the user is validated from the server it sends back an user object which contains a JWT auth token which is assigned to the user object in the store. Now lets assume that the user came back after 3 hours and tried to visit a route or perform any other action, considering that the auth token has expired by then, what would be the best way to check that(need to call axios post to check it) and redirect user to the login page. My app will have loads of components so I know I can write logic to check the token valid in the mounted hook of each component but that would mean repeating it all of the components. Also I don't want to use the beforeEach navigation guard because I cannot show any visual feedback to the user like checking... or loading....
I do something similar in one of my projects, it's actually deceptively difficult to handle these types of situations, but you can add a beforeEnter guard to your protected routes, then redirect if the authentication failed.
const guard = function(to, from, next) {
// check for valid auth token
axios.get('/api/checkAuthToken').then(response => {
// Token is valid, so continue
next();
}).catch(error => {
// There was an error so redirect
window.location.href = "/login";
})
};
Then on your route you can do:
{
path: '/dashboard',
component: Dashboard,
beforeEnter: (to, from, next) => {
guard(to, from, next);
}
},
You may notice I've used location.href rather than router.push. I do that because my login form is csrf protected, so I need a new csrf_token.
Your other issue is going to be if the user tries to interact with your page without changing the route (i.e. they click a button and get a 401 response). For this I find it easiest to check authentication on each axios request and redirect to login when I receive a 401 response.
In terms of adding a loading spinner during the guard check you can simply add a loading flag to your vuex store then import your store into your router. Honestly though I wouldn't bother, on a decent production server the check will be done so quickly that the user is unlikely to ever see it.
Try Vue.JS Mixins
You can define a Global Mixin and use it via Vue.use(myMixin) - then all Components will inherit this mixin. If you define a mounted or probably better activated hook on the mixin, it will be called on every component.
There you can use everything a component can do - this will point to your component. And if the component also defines a hook itself, the mixin hook of the same type will run before the components own hook.
Or try a single top-level login component
We used a little different solution - we have a single component which handles everything login-related, which exists outside of the router-view in the parent index.html. This component is always active and can hide the div router-view and overlay a loading message or a login-screen. For an intranet-application this component will also use polling to keep the session alive as long as the browser stays open.
You can load of your router-navigation to this component. - So a child-component which wants to trigger a router-navigation just sets a global reactive property navigateTo which is watched by the top level authentication component. This will trigger an authentication check, possibly a login-workflow and after that the top-level component will call $router.push() With this approach you have complete control over any navigation.
You can use interceptors to silently get the auth token when some request happens.
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
const rToken = window.localStorage.getItem('rToken');
return axios.post('url/to/get/refresh/token', { rToken })
.then(({data}) => {
window.localStorage.setItem('token', data.token);
window.localStorage.setItem('rToken', data.refreshToken);
axios.defaults.headers.common['Authorization'] = 'Bearer ' + data.token;
originalRequest.headers['Authorization'] = 'Bearer ' + data.token;
return axios(originalRequest);
});
}
return Promise.reject(error);
});
Because you use vuex, you can add some state like isLoading or isChecking.
And in your router.beforeEach, you can check and set isLoading or isChecking follow your current checking state. Then you can show loading message follow this state.
In our route.js we check in beforeEnter hooks the user has token or
not.
route.js
{
path: '/dashboard',
name: dashboard,
meta: {
layout: 'home-layout'
},
components: {
default: Dashboard,
header: UserHeader
},
beforeEnter: ifAuthenticated,
}
route.js
const ifAuthenticated = (to, from, next) => {
if (localStorage.getItem(token)) {
next();
return;
}
router.push({
name: 'login',
params: {
returnTo: to.path,
query: to.query,
},
});
};