Vue3-31-路由-RouterView的name属性的作用

作用描述

<router-view> 标签是用来渲染路由对应的组件的位置;

默认情况下,一个路由是只对应一个组件的。

但是,可以通过给 <router-view> 指定 name 属性的方式,实现同时渲染多个组件的效果。

这也叫做 命名视图

注意点

1、因为一个路由需要对应多个组件,所以在进行路由配置时需要使用 components 来代替 component;
2、在使用<router-view> 时指定 name 属性,不指定的,默认是 default
3、components 中使用 key-value 的形式配置组件,
key : 就是 <router-view> 的 name 属性的值
value : 就是要渲染的组件

复制代码
路由中的配置就像下面这样 :

  {
        path:'/showAllComponents',
        name:'aroute',
        components:{ // 指定多个组件
            default : componentA,  // 默认名称 default
            first : componentB, // name = first 的 router-view
            second : componentC  // name = second 的 router-view
        },
       
    },

使用案例

复制代码
项目结构如下 :
projectName
	| -- src
		| -- App.vue # 根组件,A B C 三个组件都在这里展示
		| -- componentA.vue
		| -- componentB.vue
		| -- componentC.vue
		| -- router.ts # 路由配置的文件
		| -- mian.ts # 程序的入口ts文件
	| -- index.html # 项目页面入口文件

下面的案例代码只展示重点的部分:

router.ts 路由配置

ts 复制代码
// 导入 定义路由的两个方法
import {createRouter,createWebHistory}  from 'vue-router'

// 引入两个组件
import componentA from "./componentA.vue";
import componentB from "./componentB.vue";
import componentC from "./componentC.vue";

// 声明路由跳转的路径与组件的对应关系
const routsList = [
    {
        path:'/showAllComponents',
        name:'aroute',
        components:{
            default : componentA,
            first : componentB,
            second : componentC
        },
    },
]

// 创建路由的实例对象
const routerConfigObj = createRouter({
    history:createWebHistory('abc'), // 带一个参数,表示是路由的一个前缀
    routes:routsList // 指定路由的配置列表
})

// 导出路由的对象
export default routerConfigObj;

App.vue 根组件内容

html 复制代码
<template>
    <div class="basediv">
      
        APP.vue 中的 msg : {{ msg }}
        
        <br><br><br>
        <!-- router-view 进行目标组件的展示 -->
        <router-view></router-view>
        <router-view name="first"></router-view>
        <router-view name="second"></router-view>
    
    </div>
   
</template>
    
<script setup lang="ts">

	// 引入 provide 方法
    import { ref } from 'vue'

    // 声明父组件的一个变量
    const msg = ref('这是App根组件的msg变量')

</script>
    
<style scoped>
    .basediv{
        width: 600px;
        height: 400px;
        border: 1px solid red;
    }
</style>

运行效果

相关推荐
梁辰兴3 小时前
企业培训笔记:Vue3前端框架配置
笔记·前端框架·npm·vue·vue3·node
知识分享小能手2 天前
Vue3 学习教程,从入门到精通,使用 VSCode 开发 Vue3 的详细指南(3)
前端·javascript·vue.js·学习·前端框架·vue·vue3
雪碧聊技术3 天前
v-for的用法及案例
vue3·uniapp·v-for·购物车案例
Fanmeang4 天前
OSPF路由过滤
运维·网络·华为·ip·路由·ospf·路由过滤
Modify_QmQ7 天前
leaflet【十一】地图瓦片路径可视化
gis·vue3·leaflet·leafletmapblock
百锦再7 天前
RabbitMQ用法的6种核心模式全面解析
分布式·rabbitmq·路由·消息·通道·交换机·代理
ldj202017 天前
vue3整合element-plus
vue3
夜空孤狼啸22 天前
前端常用拖拽组件库(vue3、react、vue2)
前端·javascript·react.js·typescript·前端框架·vue3
sunshine_程序媛22 天前
vue3中的watch和watchEffect区别以及demo示例
前端·javascript·vue.js·vue3
Fanmeang24 天前
IP路由基础
网络·网络协议·华为·路由·静态路由·路由表·动态路由