vue-router redirect to default path issue

若如初见. 提交于 2019-12-13 11:54:43

问题


I want to default to a specific page when user navigates to the root path ie when used goes to myapp.com I want to redirect them to myapp.com/defaultpage

My current code is

index.js

import Full from '../containers/Full'
import DefaultView from '../views/DefaultView'

export default new Router({
  mode: 'history',
  linkActiveClass: 'open active',
  scrollBehavior: () => ({ y: 0 }),
  routes: [
    {
      path: '/',
      redirect: '/defaultview',
      name: 'home',
      component: Full,
      children: [
        {
          path: '/defaultview',
          name: 'defaultview',
          component: DefaultView
        },
        {
          path: '*',
          component: NotFoundComponent
        }
    }
]})

As it is when user goes to myapp.com I get a '404 page not found' - ie the NotFoundComponent. Only when I type in myapp.com/defaultview can I get to the correct page.

Any ideas?


回答1:


When using children remove url prefix of the parent

ex: change "/defaultview" to defaultview remove the parent path component, so the actual code should be like this

routes: [
{
  path: '/',
  redirect: '/defaultview',
  name: 'home',
  component: Full,
  children: [
    {
      path: 'defaultview', /* changed */
      name: 'defaultview',
      component: DefaultView
    },
    {
      path: '*',
      component: NotFoundComponent
    }
  ]
}

reference Nested Routes




回答2:


Try this code:

routes: [
    {
      path: '/',
      redirect: '/defaultview'
    },
    {
      path: '/defaultview',
      name: 'defaultview',
      component: DefaultView
    },
    {
      path: '*',
      component: NotFoundComponent
    }
]



回答3:


You can do it using 1 line of code, i.e. by adding router.replace("myPath");. Full code:

import Vue from "vue";
import Router from "vue-router";
import MyComponent from "./my-component";

Vue.use(Router);

const routes = [
  { path: "/myPath", name: "myPath", component: MyComponent }
];

const router = new Router({
  mode: "history", // Remove the hash from the URL, optional.
  routes
});

router.replace("myPath");

export default router;


来源:https://stackoverflow.com/questions/44060414/vue-router-redirect-to-default-path-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!