项目目录:

首先看下,我在User.vue下面挂载两个子组件:Posts.vue和Profile.vue。

两个子组件的代下如下:

Posts.vue代码:

// Posts.vue里面的内容

<template>
    <div>
        <h2>Posts页面</h2>
    </div>
</template>

<script>
    export default {
        
    }
</script>

<style lang="scss" scoped>

</style>

Profile.vue代码:

// Profile.vue里面的内容

<template>
    <div>
        <h2>Profile页面</h2>
    </div>
</template>

<script>
    export default {
        
    }
</script>

<style lang="scss" scoped>

</style>

两个子组件挂载到index.js里面:

index.js代码如下:

// index.js里面的内容

import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
// import Posts from '@/views/Posts.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path:'/user',
    name:'user',
    component:()=>import('@/views/User.vue'),
    // props:true,
    children:[
      {
        path:'posts',
        component:()=>import('@/views/Posts')
      },
      {
        path:'/profile',
        component:()=>import('@/views/Profile')
      }
    ]
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

下图是挂载的信息:

 可以看出,两个path不一样!一个有/,另外一个没有。

父组件App.vue代码如下:

// App.vue里面的内容

<template>
  <nav>
    <router-link to="/">首页</router-link> |
    <router-link to="/about">关于</router-link> |
    <router-link to='/user'>User</router-link>  |
    <router-link to='user/posts'>user/posts</router-link> |
    <router-link to='user/profile'>user/profile</router-link>

  </nav>
  <router-view/>
  <!-- <router-view></router-view> -->
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}
</style>

运行结果如下:

 

 上图可以看出,带/的子组件,页面显示出来了,没有带/的页面没有显示出来。

Logo

前往低代码交流专区

更多推荐