I'm in trouble with vue-router :) I create a simple map for router :
module.exports = {
'/': {
component: require('./views/home')
},
'/auth/login': {
component: require('./views/auth/login')
},
'/auth/register': {
component: require('./views/auth/register')
},
'/resumes': {
component: require('./views/resumes')
},
// 404 NotFound
'*': {
component: {
template: "not found"
}
}
};
And define router to vue and it works perfectly. My home page js codes :
module.exports = {
inherit: true,
template: require('./template.html'),
ready: function() {
if(this.isLoggedIn)
this.$route.router.go('/resumes');
}
};
I want to load resumes page if user logged in.
When I use it in any event or with v-link directive, it works normal.
But if I use it on ready function, it duplicates pages. It calls home page and appends second page on it.
IMG : http://imageshack.com/a/img540/9409/3DK1ZL.jpg
Whats wrong? How can I solve it? I am dealing about 4 days with this problem. Please help me guys.
this.$route.router.go('/resumes') has already been removed since Vue 2.0.
Related
I have
these simple route/URL when I am in a car details page
http://localhost:8080/car/1
I am using vue2; what is the best way to check if I am on a car page?
I normally
would have checked for the first segment of the URL, but I wasn't sure if that is the best future-proof approach.
Questions
Should I use JS to detect what page I am ?
Should I use Vue functionality to access the router object?
Why would one decide to pick one over another?
You could provide a name for your route inside the routes definition like :
{
path: '/car/{id}',
name: 'car',
component: CarView
},
then access it using this.$route.name or you could parse the this.$route.path to get the name using String object methods
Perhaps, try using: router.currentRoute.path, where router is:
import Router from "vue-router";
Vue.use(Router);
const routes = [
{ path: "/", component: Home },
{ path: "/test1", component: Test1 },
{ path: "/test2", component: Test2 }
];
const router = new Router({
routes
});
console.log('Current route: ', router.currentRoute.path);
I'm trying to setup navigation guards in my Nuxt app to redirect users to the login screen if they are not authenticated via Firebase Authentication. When the user attempts to navigate my router middleware is redirecting them successfully, but on page load they are not being redirected.
I did realize that the middleware is not even being fired on page load. I found a recommendation to try a plugin to handle the redirect on page load, but it is not working. Calling router.push from within the plugin does not redirect the user.
Here are a few notes on my setup. This is being deployed to firebase hosting directly as a SPA with no SSR. It's using the Nuxt-Firebase module with Firebase Authentication service.
// nuxt.config.js
target: "server", // server here works when I deploy to firebase, but I also tried static
ssr: false,
middleware: ["auth"],
plugins: [
"~/plugins/auth.js",
],
modules: [
[
"#nuxtjs/firebase",
{
services: {
auth: {
initialize: {
onAuthStateChangedMutation:
"authData/ON_AUTH_STATE_CHANGED_MUTATION",
onAuthStateChangedAction: "authData/ON_AUTH_STATE_CHANGED_ACTION",
subscribeManually: false,
},
},
},
},
],
],
};
Here's a sample plugin I thought might solve this, but calling handleLoggedOut appears to do nothing on page load.
// --- plugin to redirect user --- /plugins/auth.js ---
export default function (context, inject) {
const auth = {
handleLoggedOut: () => {
console.log("logout handled");
context.redirect("/login");
},
};
inject("auth", auth);
}
// --- store actions --- /store/authData.js ---
actions: {
async ON_AUTH_STATE_CHANGED_ACTION(
{ commit, state, dispatch },
{ authUser, claims }
) {
if (authUser) {
// logged in
}
else {
// attempting to redirect here does not work
this.$auth.handleLoggedOut()
}
}
I'm new to Nuxt and I can't seem to find an example that solves my issue.
Any help would be greatly appreciated, thank you!
Code seems fine, But you can just use the this.$fire.auth.signOut() and you can remove the auth plugin.
Example:
// --- store actions --- /store/authData.js ---
actions: {
async signOut({ commit }, payload) {
try {
await this.$fire.auth.signOut();
// This is just a guard to avoid navigation guard error (NavigationDuplicated),
// you can remove the if block
if (!payload) {
this.$router.push('/login')
}
commit(ON_AUTH_STATE_CHANGED_MUTATION, { authUser: null})
} catch(err) {
console.log(err)
}
},
async ON_AUTH_STATE_CHANGED_ACTION(
{ commit, state, dispatch },
{ authUser, claims }
) {
if (authUser) {
// logged in
}
else {
// attempting to redirect here does not work
return dispatch('signOut')
}
}
}
The solution for redirecting users to the login on page load was to put this in my auth middleware:
export default function ({ redirect, store, route }) {
// https://nuxtjs.org/docs/internals-glossary/context#redirect
if (!store || !store.getters || !store.getters["authData/isLoggedIn"]) {
window.onNuxtReady(() => {
window.$nuxt.$router.push("/login");
});
}
}
I have 2 links like below. When I click on any one the first time, it navigates to it but when I click on the second link after that, the url changes but it does not navigate to it.
<li><a routerLink="/order/buyer" >Buyer</a></li>
<li><a routerLink="/order/seller">Seller</a></li>
These are my route configuration:
app.routing.module.ts
const routes: Routes = [
{
path: '',
pathMatch: 'full',
component: RootComponent,
},
{
path: '',
children: [
{
path: 'order',
loadChildren: './order/order.module#OrderModule',
}
]
}
order.module.ts
export const ROUTES: Routes = [
{
path: ':orderParty/:id',
component: OrderDetailComponent,
canDeactivate: [OrderDetailGuardService]
},
{
path: ':orderParty',
component: OrderListComponent
}
];
Tried several things, that out there but didn't work. What I have noticed is on the second click, the ngOnInit() of the 'OrderListComponent' does not get called.
You have a few options to solve this common issue in Angular, the most common one is using the solution on this GitHub thread:
https://github.com/angular/angular/issues/13831#issuecomment-319634921
constructor(private router: Router){
// override the route reuse strategy
this.router.routeReuseStrategy.shouldReuseRoute = function(){
return false;
}
this.router.events.subscribe((evt) => {
if (evt instanceof NavigationEnd) {
// trick the Router into believing it's last link wasn't previously loaded
this.router.navigated = false;
// if you need to scroll back to top, here is the right place
window.scrollTo(0, 0);
}
});
}
Another solution would to subscribe to your router params and handle change based on the new param like this article suggests:
this.activeRoute.params.subscribe(routeParams => {
this.loadUserDetail(routeParams.id);
});
https://medium.com/#mvivek3112/reloading-components-when-change-in-route-params-angular-deed6107c6bb
Yes, because route is same its the dynamic parameter that is changing. to read changed parameter you can inject router in construct and read parameter like
this.router.params.subscribe((params)=>{console.log(params)});
The route is pointing to same component hence its not re initializing.
bellow is my redirect method which is not working
goToProdPage() {
this.router.navigate([this.quoteId,'/cpq']);
window.location.reload();
}
but if i change this to
goToProdPage() {
this.router.navigate(['./'+this.quoteId+'/cpq']);
window.location.reload();
}
Then its working fine. but now i'm not able to get url param(which is quoteId) from activatedRoute in other components.
bellow is routing code in app.module.ts
const appRouter :Routes = [
{path:'login', component: loginPage},
{path:':quoteId/cpq', component: cpqPage},
{path:'', redirectTo:'/login', pathMatch:'full'},
]
You don´t need window.location.reload(); which will skip the cache and reload the same page, change it as
goToProdPage() {
this.router.navigate([this.quoteId, 'cpq']);
}
I'm using Vue and Vue Router in a SPA. In a view component I query a repository for a resource. If the resource is not found I want to show a 404 page whilst keeping the URL.
I.e. if I visit /foo/non-existant-id then a 404 page should be shown in place of the show page for the foo resource.
For clarity here is my router map:
router.map({
'/foo/:id': {name: 'foo-show', component: FooShowPage},
// Utilities
'/': { name: 'home', component: HomePage },
'*': { name: '404', component: NotFoundPage }
})
And in my FooShowPage I do the following:
ready () {
// fetch the foo from the repo (app.foos)
app.foos.fetchById(this.$route.params.id).then(foo => {
this.foo = foo
}).catch(e => {
// foo is not found show a 404 page
// using this.$route.router.go({name: '404'}) does not work as route is a wildcard
console.warn(e)
})
}
Essentially it would probably involve replacing the FooShowPage in the router view with NotFoundPage, or redirecting to a defined 404 page whilst keeping the browser history untouched.
You need to set a route for 404 page and then redirect unmatched routes to it. I use a router.redirect after the map to do such things.
router.map({
'/': { name: 'home', component: HomePage },
'/foo/:id': {name: 'foo-show', component: FooShowPage},
'/404': {name: 'not-found', component: NotFound}
})
router.redirect({
'*': '/404'
})
All routes that are NOT listed in the map will then be redirected to /404
Found a solution at Vue.js forum — use navigation guard:
import store from '../store'
{
path: '/lavori/:lavoro',
name: 'lavoro',
component: Lavoro,
beforeEnter: (to, from, next) => {
function isValid (id) {
return store.getters.resourceByID(id) !== undefined
}
if (!isValid(to.params.id)) {
next({ name: 'not-found' });
}
next();
}
},
Edit1: need to import store to get access to getters, from this Github issue and this question
Still a question how to leave same (requested) URL
The best I've figured out how to do is to use a global interceptor with Axios to redirect all 404 responses received through the API the 404 route. However that does change the url to /404 like #Leo's answer.
const http = axios.create({
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
});
// Add some global response intercepters
http.interceptors.response.use(function (response) {
// For successes just continue as normal
return response;
}, function (error) {
// If we have a 404 redirect to the error page replacing the history
if (error.response.status === 404) {
return router.replace({ name: 'notfound' });
}
return Promise.reject(error);
});
export default http;