在Vue中,可以使用Vue Router来设置子路由。下面是一个设置子路由的示例:

  1. 首先,在主路由文件(通常是main.js)中引入Vue Router,并创建一个新的Router实例:
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import Home from './components/Home.vue'
import About from './components/About.vue'
import Contact from './components/Contact.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About },
    { path: '/contact', component: Contact }
  ]
})

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')
  1. 在App.vue(或其他根组件)中,添加一个<router-view>标签,用于渲染子路由组件:
<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>
  1. 在需要设置子路由的组件中,创建一个新的<router-view>标签,并在父路由中设置子路由的路径和组件:
<template>
  <div>
    <h1>About</h1>
    <router-view></router-view>
  </div>
</template>
  1. 在父组件的路由配置中,使用children属性来定义子路由:
const router = new VueRouter({
  routes: [
    { path: '/', component: Home },
    { 
      path: '/about', 
      component: About,
      children: [
        { path: 'info', component: AboutInfo },
        { path: 'contact', component: AboutContact }
      ]
    },
    { path: '/contact', component: Contact }
  ]
})

在上述示例中,About组件是一个父路由,它包含了两个子路由AboutInfoAboutContact。当访问/about路径时,About组件会被渲染,并在该组件中的<router-view>标签中渲染匹配的子路由组件

vue如何设置子路由

原文地址: https://www.cveoy.top/t/topic/isXo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录