Vue路由器重定向到默认路径问题

Vue.js

樱蛋蛋

2020-03-16

当用户导航到根路径时,我想默认到特定页面,即当使用到myapp.com时,我想将它们重定向到myapp.com/defaultpage

我当前的代码是

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
        }
    }
]})

当用户转到myapp.com时,我得到一个“找不到404页”的信息,即NotFoundComponent。只有输入myapp.com/defaultview时,我才能进入正确的页面。

有任何想法吗?

第1730篇《Vue路由器重定向到默认路径问题》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
Mandy小卤蛋凯 2020.03.16

您可以使用1行代码(即添加)来完成此操作router.replace("myPath");完整代码:

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;

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android