{"title":"Vue Router 子路由设置教程 - 完整指南","description":"学习如何在Vue中使用Vue Router设置子路由,包含完整示例和代码解释。了解如何创建子路由、定义子路由路径、渲染子路由组件等,构建更复杂的单页面应用。","keywords":"vue, vue router, 子路由, 路由设置, vue 路由, 前端框架, 单页面应用","content":"在Vue中,可以使用Vue Router来设置子路由。下面是一个设置子路由的示例:\n\n1. 首先,在主路由文件(通常是main.js)中引入Vue Router,并创建一个新的Router实例:\n\njavascript\nimport Vue from 'vue'\nimport VueRouter from 'vue-router'\nimport App from './App.vue'\nimport Home from './components/Home.vue'\nimport About from './components/About.vue'\nimport Contact from './components/Contact.vue'\n\nVue.use(VueRouter)\n\nconst router = new VueRouter({\n routes: [\n { path: '/', component: Home },\n { path: '/about', component: About },\n { path: '/contact', component: Contact }\n ]\n})\n\nnew Vue({\n router,\n render: h => h(App),\n}).$mount('#app')\n\n\n2. 在App.vue(或其他根组件)中,添加一个<router-view>标签,用于渲染子路由组件:\n\nhtml\n<template>\n <div id="app">\n <router-view></router-view>\n </div>\n</template>\n\n\n3. 在需要设置子路由的组件中,创建一个新的<router-view>标签,并在父路由中设置子路由的路径和组件:\n\nhtml\n<template>\n <div>\n <h1>About</h1>\n <router-view></router-view>\n </div>\n</template>\n\n\n4. 在父组件的路由配置中,使用children属性来定义子路由:\n\njavascript\nconst router = new VueRouter({\n routes: [\n { path: '/', component: Home },\n { \n path: '/about', \n component: About,\n children: [\n { path: 'info', component: AboutInfo },\n { path: 'contact', component: AboutContact }\n ]\n },\n { path: '/contact', component: Contact }\n ]\n})\n\n\n在上述示例中,About组件是一个父路由,它包含了两个子路由AboutInfo和AboutContact。当访问/about路径时,About组件会被渲染,并在该组件中的<router-view>标签中渲染匹配的子路由组件。"}

Vue Router 子路由设置教程 - 完整指南

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

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