Vue:关于router-view的命名视图、传参、自定义事件

1、概述

目前根据项目要求,需要实现这么一个需求:
(1)一级目录在顶部,二级目录在侧边,右边是main主要内容
(2)main主要内容包含:固定的地图组件,以及left,bottom,right组件
(3)left,bottom,right组件根据二级菜单的点击,是可变的,
(4)在二级菜单中可能会使用同一地图组件(保活),也可能不会展示地图组件
(5)left,bottom,right组件要实现跟地图组件的通信

在这里插入图片描述

上述是结合router-view的嵌套、命名视图、自定义事件实现效果,在实现的过程中,对于<router-view>多了一层理解。下面就命名视图和自定义事件做个记录。

2、命名视图

具体的官方说明请参考:→官方地址

这里我只说下个人的理解:

  1. <router-view>可以存在多个。
  2. <router-view>组件有个name属性
  3. <router-view>可以当作一个普通组件来看待的,因此可以绑定自定义属性传值和绑定自定义事件

(1)什么叫可以存在多个?

上代码:

<template>
  <div id="app">
    <router-view />
  </div>
</template>

这个代码其实是我们经常使用<router-view />的一个场景。
那如果按照下面这样写,能渲染出来嘛?

<template>
  <div id="app">
    <router-view />
    <router-view />
  </div>
</template>

答案是:可以的。
问题时:两个<router-view />渲染的内容是一样的。
解决方案:用name属性进行区分(命名视图)

(2)命名视图是什么?

命名视图,其实跟具名插槽有点类似。
我们常规使用<router-view>,其实只是作为一个路由组件渲染的占位符。
而<router-view>组件是有name属性的,加入name属性后可以进行具名渲染。如果 router-view 没有设置名字,那么默认为 default。

具体要如何实现?

<template>
  <div id="app">
    <router-view name="LeftSidebar" />
    <router-view />
  </div>
</template>

仅仅这样还是无法实现,需要同时修改router/index.js文件:

const routes =[
	{
    
    
	  path: '/page5',
	  name: 'page5',
	  components: {
    
    
	    LeftSidebar:page5,
	    default: page1
	  }
	}
]

一个视图使用一个组件渲染,因此对于同个路由,多个视图就需要多个组件。需要使用 components 配置 (带上 s)

(3) <router-view>也是一个普通组件

// LeftSidebar.vue
<template>
  <div>
    <div>LeftSidebar【1】</div>
    <div @click="dataCommunication">组件通信测试</div>
  </div>
</template>

<script>
export default {
      
      
  name: 'LeftSidebar',
  methods: {
      
      
    dataCommunication () {
      
      
      this.$emit('dataCommunication', '数据通信测试')
    }
  }
}
</script>
// page4.vue
<template>
  <div class="main">
    <router-view
      class="left"
      name="LeftSidebar"
      @dataCommunication="dataCommunication"
    ></router-view>
    <div class="middle">
      <div class="top">
        <div @click="count++">固定的地图,保活测试: {
   
   { count }}</div>
        <div style="color: red">{
   
   { info }}</div>
      </div>
      <router-view class="bottom" name="BottomSidebar"></router-view>
    </div>
    <router-view class="right" name="RightSidebar"></router-view>
  </div>
</template>

<script>
export default {
      
      
  name: 'page4',
  data () {
      
      
    return {
      
      
      count: 1,
      info: ''
    }
  },
  methods: {
      
      
    dataCommunication (info) {
      
      
      console.log(info, '----------->info')
      this.info = info
      alert('收到LeftSidebar组件的通信数据')
    }
  }
}
</script>

完整代码可以考虑E:/yztdemo

猜你喜欢

转载自blog.csdn.net/Litt_White/article/details/129934443