一、Vue中的嵌套路由
1.App.vue中的代码
<template> <div id="app"> <router-view/> </div> </template>
2.router/index.js: children中的子路由,path 不加 '/',访问main,先获取main对应的组件,对应的路由出口在App.vue中,redirect的属性值为访问 父组件时,会强制访问父组件下某个子组件,该组件对应的路由出口在父组件中
import Vue from 'vue' import VueRouter from 'vue-router' import HomeView from '../views/HomeView.vue' Vue.use(VueRouter) // 路由中的文件加载对应的是app.vue的路由出口 // 路由中的文件的子文件加载对应的是该文件中的路由出口 // 如:main下面的news的加载,是在main中的routerview中显示的 const routes = [ { path: '/login', component: () => import( '../views/LoginView.vue') }, { path: '/main', component: () => import( '../views/MainView.vue'), redirect:'/main/news', children:[ { path: 'home', name: 'home', component: HomeView }, { path: 'about', name: 'about', component: () => import( '@/views/AboutView.vue') }, { path: 'news', component: () => import('@/views/NewsView.vue') }, { path: 'editor', component: () => import('@/views/EditorView.vue') }, { path: 'product', component: () => import('@/views/ProductView.vue') }, { path: 'case', component: () => import('@/views/CaseView.vue') } ] } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
3.LoginView.vue
<template> <div> <h1>登录</h1> {{ $store.state.token }} <el-form ref="form" :rules="rules" :model="form" label-width="80px"> <el-form-item label="账号" prop="username"> <el-input v-model.trim="form.username" ></el-input> </el-form-item> <el-form-item label="密码" prop="password"> <el-input type="password" v-model="form.password" ></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="onSubmit">登录</el-button> </el-form-item> </el-form> </div> </template> <script> export default { methods:{ onSubmit(){ this.$refs.form.validate((valid) => { if (valid) { this.$store.dispatch('setTokenAsync',this.form); } else { console.log('error submit!!'); return false; } }); } }, data(){ return { form:{}, rules: { username: [ { required: true, message: '请输入账号', trigger: 'blur' }, { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' } ], password: [ { required: true, message: '请输入密码', trigger: 'blur' } ] } } } } </script> <style lang="scss" scoped> </style>
4.MainView.vue: 在MainView.vue中,访问对应的子路由时,to='/父组件访问时对应的path/子组件对应的path',此时访问的子组件 ,显示对应的路由出口在MainView.vue文件中。
<template> <div> <!-- MainView.vue页面对应的路由出口在app.vue --> <nav> <router-link to="/main/home">Home</router-link> | <router-link to="/main/about">About</router-link> | <router-link to="/main/news">新闻列表</router-link> | <router-link to="/main/product">产品列表</router-link> | <router-link to="/main/case">案例列表</router-link>| <router-link to="/main/editor">编辑器</router-link> </nav> <!-- 点击MainView.vue页面上的链接,对应的视图对应的路由出口在这里 --> <router-view></router-view> </div> </template> <script> export default { } </script>
5.页面效果
访问login
访问main
标签:Vue,views,component,嵌套,vue,import,path,路由 From: https://www.cnblogs.com/njhwy/p/18576292