VUE3前端笔记 Mitt事务总线使用方法

1. 第三方总线插件mitt

(1)Vue CLI图形界面安装

d:\aboutus.Vue>vue ui
🚀  Starting GUI...
🌠  Ready on http://localhost:8000

打开浏览器输入http://localhost:8000进入Vue CLI图形界面
在这里插入图片描述
查找并安装mitt依赖
在这里插入图片描述

(2)npm命令方式安装

npm install -S mitt

//-S安装为dependencies,即用于发布到生产环境

d:\aboutus.Vue>npm install -S mitt

2. 全局总线

①vue入口文件main.js中挂载全局属性

//导入vue创建命令
import { createApp } from 'vue';
//导入vue入口组件
import App from './App.vue';
//导入插件mitt
import mitt from "mitt"
...
//创建Vue应用实例
const app = createApp(App)
//挂载事务总线为全局属性
app.config.globalProperties.$mybus = new mitt()
...

app 是自定义Vue实例名
mybus 是自定义总线属性名

②组件中发送事件/发布

this.$mybus.emit('自定义事件名称','数据');

③组件中接收事件/订阅

this.$mybus.on('自定义事件名称',data=>{
	console.log(data); //控制台输出接收到的数据
})

④移除总线事件监听

this.$mybus.off('自定义事件名称')

3. 组件总线

①封装自定义事务总线文件mybus.js

创建新的js文件,自定义命名
/src/myplugins/mybus.js

import mitt from 'mitt'
export default mitt()

②在发送和接收组件中分别导入mybus.js

<template>
...
</template>
<script>
import mybus from "../myplugins/mybus";
...
export default {
...
}
</script>
<style>
...
</style>

注意:
组件中导入文件mybus.js使用相对路径

③发送事件/发布

mybus.emit('自定义事件名称','数据');

④接收事件/订阅

mybus.on('自定义事件名称',data=>{
	console.log(data);//接收到的数据
})

⑤移除总线事件监听

mybus.off('自定义事件名称');

4. 视频点播使用案例

视频列表有多个视频信息,需要根据用户动态选择决定哪个视频信息同步给播放器组件页,无法用父子数据绑定的方式实现,依靠事务总线动态发送选中的点播信息到播放器组件页面。

(1)核心文件结构示意

 myvideo
 |--- dist
 |--- node_modules
 |--- public
 		|--- index.html
 |--- src
 		|--- assets
 		|--- componets
 			|--- Player.vue
 		|--- myplugins
 			|--- mybus.js
 		|--- router
 			|--- router.js
 		|--- static
 		|--- views
 			|--- List.vue
 		|--- App.vue
 		|--- main.js
...

(2)封装自定义事务总线文件

mybus.js

import mitt from 'mitt'
export default mitt()

(3)VUE应用入口挂载全局属性

main.js

import { createApp } from 'vue';
import App from './App.vue';

//创建Vue应用实例
const app = createApp(App)

//挂载事务总线为全局属性
import mitt from "mitt";//第三方事务总线
app.config.globalProperties.$mybus = new mitt()

//挂载路由
import router from './router/router';
app.use(router)

//挂载应用页面
app.mount('#app')

(4)点播列表页面发送数据

List.vue

<template>
	<div class="boxed">
		<h2> <span class="text-primary">Gallery</span> 视频点播</h2>
		<div class="section-inner nopaddingbottom">
			<ul>
				<li class="nopadding-lr hover-item" v-for="item in galleryArray" :key="item.vod_id">
					<img :src="item.cover" alt="" style="width: 320px;height: 240px">
					<div class="overlay-item-caption smoothie wow fadeIn" data-wow-delay="0.5s">
						<div class="vertical-center smoothie">
							<h3>{{item.title}}</h3>
						</div>
					</div>
					<div class="hover-item-caption smoothie">
						<h3 class="vertical-center smoothie"><a href="#" @click="showVideo(item.title,item.vod_id,item.cover)" class="smoothie btn btn-primary btn-white page-scroll" title="view article">播放</a></h3>
					</div>
				</li>
			</ul>
		</div>
	</div>
	<VideoPlayer v-show="showVideoPlayer" :showVideoPlayer="showVideoPlayer"></VideoPlayer>
</template>

<script>
import VideoPlayer from "../components/VideoPlayer";//视频播放组件
export default {
	name: 'List',
	components: {
		VideoPlayer
	},
	props: {
	},
	data(){
		return {
			showVideoPlayer:false,//视频播放器显示开关
			vodData:{},//准备播放的视频数据
			galleryArray:[
				{
					'title':'这是第1个视频',
					'url':'https://1400329073.vod2.myqcloud.com/d62d88a7vodtranscq1400329073/0f02d4155285890799710670616/video_10_3.m3u8',
					'cover':'https://main.qcloudimg.com/raw/6c2fe22b10919aca0c1d0226499a0f63.png'
				},
				{
					'title':'这是第2个视频',
					'url':'https://1256993030.vod2.myqcloud.com/d520582dvodtransgzp1256993030/7732bd367447398157015849771/v.f40.mp4',
					'cover':'https://main.qcloudimg.com/raw/99c05e75f0d417df33942d18dad2f509.jpg'
				},
			]
		};
	},
	methods: {
		//播放作品
		showVideo(title,vod_id,cover) {
			this.vodData = {
				'title':title,
				'url':url,
				'cover':cover
			};
			this.showVideoPlayer = true;//显示播放器组件
			this.$mybus.emit('vodData_Bus', this.vodData);//传输VOD视频数据
		},
	},
	created() {

	},
	mounted() {
		
	}
}
</script>

<style scoped>

</style>

(5)播放器组件接收数据

Player.vue

<template>

<!--VideoPlayer-->
<div class="video-player-container">
	<i class="close-btn ion-close right-boxed" id="btnClose" @click="closeVideo()">正在播放...<br>{{vodData.title}}<br>点击关闭</i>
	<div class="player-content">
		<div id="the-player">
			<div id="PlayerVideo" class="player-video" ref="playerRef"></div>
		</div>
	</div>
</div>
<!--VideoPlayer end-->

</template>

<script>
import {TcPlayer} from 'tcplayer';//TcPlayer-2.3.3 TCPlayerLite
export default {
	name: 'VideoPlayer',
	components: {
	},
	data() {
		return {
			videoObject: null, //储存播放器实例化属性
			playerObject: null, //储存播放器实例化对象
			vodData:{
				'title':'',
				'vod_id':'',
				'cover':''
			}
		};
	},
	props: {
	},
	methods: {
		// 实例化TCPlayer播放器
		initTcPalyer(url, cover) {
			this.playerObject = new TcPlayer("PlayerVideo", {
				m3u8: url,
				autoplay: true,
				width: "100%",
				height: "100%",
				preload: "meta",
				loop: false,
				poster: cover,
				live: false,
				wording: {
					1: "网络错误!",
					2: "网络错误!",
					3: "视频解码错误。",
					4: "当前系统不支持播放该视频格式。",
					5: "当前系统不支持播放该视频格式!",
					12: "请填写视频播放地址。",
					13: "主播已离开,请稍后再来!",
					1001: "网络已断开(NetConnection.Connect.Closed)。",
					1002: "获取视频失败,请检查播放链接是否有效。",
					2048: "无法加载视频文件,跨域访问被拒绝。"
				}
			});
		},
		// 新建TCPlayer播放器
		newTcPlayer(url, cover) {
			this.initTcPalyer(url, cover);
			this.videoObject = document.querySelector("video");
			this.videoObject.setAttribute("x5-playsinline", "");
			this.videoObject.setAttribute("playsinline", "");
			this.videoObject.setAttribute("webkit-playsinline", "");
			this.videoObject.setAttribute("poster", "");
			this.videoObject.setAttribute("x-webkit-airplay", "allow");
			this.videoObject.setAttribute("preload", "auto");
			this.videoObject.setAttribute("muted", "");
			setTimeout(()=>{
				this.videoObject.play();
			},1000);
		},
		cleanPlayer(){
			this.playerObject.destroy();//销毁播放器实例
		},
		closeVideo(){//点击关闭遮罩层
			this.cleanPlayer();//销毁播放器
			this.$parent.showVideoPlayer = false;//关闭播放器组件层
		},
		
	},
	created() {
	},
	mounted() {
		//接收点播数据
		this.$mybus.on("vodData_Bus",data=>{
			this.vodData = data;
			this.newTcPlayer(this.vodData.url, this.vodData.cover);//新建TcPlayer播放器
		});
	}
}
</script>

<style scoped>
@import "//imgcache.qq.com/open/qcloud/video/tcplayer/tcplayer.min.css";
.video-player-container {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	margin:0 auto;
	background-color: rgba(0, 0, 0, 0.8);
	z-index: 1000;
}
.video-player-container p{
	padding:5px 5px 5px 15px;
	line-height:2;
}
.player{
	margin: 0 auto;
}
.player-content {
	position: absolute;
	width: 99%;
	top: 50%;
	left: 50%;
	-webkit-transform: translateY(-50%) translateX(-50%);
	transform: translateY(-50%) translateX(-50%);
	background-color: rgba(0, 0, 0, 0.5);
}
.close-btn{
	position:absolute;
	z-index:2;
	top:2.3rem;
	font-size:1.6rem;
	line-height:1;
	color:#fff;
	cursor:pointer;
	margin-top:.8rem;
	-webkit-transition:all .3s ease;
	-o-transition:all .3s ease;
	transition:all .3s ease
}
.close-btn:hover{
	color:#f3ca2f
}
</style>

(6)其他页面

App.vue

<template>
  <router-view/>
</template>

<script>
</script>

router.js

import { createRouter, createWebHistory } from 'vue-router'
import List from '../views/List.vue'

const routes = [
  {
    path: '/',
    name: 'List',
    component: List
  },

]
const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <meta name="format-detection" content="telephone=yes"/>
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title>老富工作室</title>

    <link rel="shortcut icon" href="favicon.png">
    <link rel="apple-touch-icon" href="apple-touch-icon.png">
    <link rel="apple-touch-icon" sizes="72x72" href="apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="114x114" href="apple-touch-icon-114x114.png">

    <link href="//fonts.googleapis.com/css?family=Montserrat:500,600,700&display=swap" rel="stylesheet">
    <link href="//fonts.googleapis.com/css?family=Poppins:300,400,400i&display=swap" rel="stylesheet">

  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->

    <!--JS-->
    <script src="//cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="//cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.min.js"></script>
    
  </body>
</html>

本章完


  • 35
    点赞
  • 99
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
Vue3中,官方建议使用外部的、实现了事件触发器接口的库来实现事件总线的功能,而mitt是其中一个常用的选择。mitt是一个非常小巧的库,只有200字节大小,并且支持全部事件的监听和批量移除。它不依赖于Vue实例,可以在不同的框架或项目中使用,例如React、Vue甚至是jQuery项目都可以使用同一个mitt库来实现事件总线的功能。在使用mitt时,你需要先安装mitt库(npm i mitt -s),然后可以通过mitt()创建一个mitt实例,并使用其提供的API来进行事件的绑定、触发和解绑操作。 下面是一些mitt库的常用API: - `emit(name, data)`:触发事件,其中`name`是要触发的事件名称,`data`是需要传递的参数。 - `on(name, callback)`:绑定事件,其中`name`是要绑定的事件名称,`callback`是触发事件后执行的回调函数。 - `off(name)`:解绑事件,其中`name`是需要解绑的事件名称。 在Vue3中使用mitt库可以参考以下步骤: 1. 首先,你需要安装mitt库(npm i mitt -s)。 2. 然后,在需要使用事件总线的组件中引入mitt库,例如在你的`bb.vue`组件中,你可以使用`import bus from "../utils/EventBus"`来引入mitt库。 3. 在需要发出事件的地方(例如点击按钮时),可以使用`bus.emit("data", 18)`来触发名为"data"的事件,并传递参数18。 希望这个回答对你有帮助!如果你还有其他问题,请随时提问。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值