Vue实现嵌套路由

217 阅读1分钟

Vue可以使用Vue Router来实现嵌套路由。嵌套路由允许你在一个父路由下定义多个子路由,从而创建更复杂的应用程序结构。

首先,你需要安装Vue Router。可以通过以下命令使用npm进行安装:

npm install vue-router

安装完成后,在你的Vue项目中创建一个router文件夹,并在其中创建一个index.js文件,用于定义和配置路由。

在index.js文件中,你可以按照以下方式设置嵌套路由:

import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

// 导入组件
import Home from '../views/Home.vue';
import About from '../views/About.vue';
import Contact from '../views/Contact.vue';
import Profile from '../views/Profile.vue';

// 定义路由
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About,
    children: [
      {
        path: 'contact',
        name: 'Contact',
        component: Contact
      },
      {
        path: 'profile',
        name: 'Profile',
        component: Profile
      }
    ]
  }
];

// 创建路由实例
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
});

export default router;

在上述代码中,我们定义了四个组件:Home、About、Contact和Profile。然后,我们在routes数组中定义了两个路由,一个是根路由'/'对应Home组件,另一个是/about对应About组件,并且在About组件中定义了两个子路由:/about/contact对应Contact组件和/about/profile对应Profile组件。

接下来,在你的Vue根组件中,可以通过使用标签来渲染嵌套路由的内容:

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

最后,在你的main.js文件中,将router实例导入并挂载到Vue实例上:

import Vue from 'vue';
import App from './App.vue';
import router from './router';

new Vue({
  router,
  render: h => h(App)
}).$mount('#app');

现在,你就可以在Vue应用程序中使用嵌套路由了。在浏览器中访问根路由'/'时,将会渲染Home组件;访问'/about'时,将会渲染About组件;访问'/about/contact'时,将会渲染Contact组件;访问'/about/profile'时,将会渲染Profile组件。