Vue Framework Usage Guide
ZWPlayer provides a dedicated interface package for the Vue framework, supporting both Vue 2.x and Vue 3.x versions.
1. Vue 3.x
1.1 Installation Steps
1. Install Vue Interface Package
You can install the vue3.x interface package for zwplayer using the following command:
npm i zwplayervue3 --save
2. Verify Installation
After successful installation, a zwplayer core library directory will be automatically generated in the project’s public directory. This directory must be built and published along with the project.
3. Version Requirements
- Vue 3.x
- Supports Vite and Webpack build tools
1.2 Component Registration
zwplayervue3 supports two component registration methods: local registration and global registration. Local registration is recommended for actual projects.
Local Registration (Recommended)
Import and register in the component where it is used:
import { zwplayer } from 'zwplayervue3'
export default {
name: 'zwplayer-demo',
components: {
zwplayer // Local registration component
},
data() {
return {
movieUrl: 'https://cdn.zwplayer.com/media/VMAP9lxJvRpgn5sP3lV6rQ9qkzQmh5psggso3185.mp4',
playerOpen: true,
player: null
};
},
methods: {
onPlayerReady() {
console.log('player ready event.');
// Get player instance
this.player = this.$refs.zwplayerRef;
},
onPlayerMediaEvent(event) {
console.log('media event:', event.type);
},
sendDanmu(danmuText) {
console.log('sendDanmu:', danmuText);
// Call websocket or other methods to actually send the danmaku
}
}
}
Advantages:
- Load on demand, reducing unnecessary code
- Clearer component dependency relationships
- Easier code maintenance and refactoring
- Better TypeScript support
Global Registration (Optional)
If you need to use it in multiple components, you can perform global registration in the main.js or main.ts file:
import { createApp } from 'vue'
import App from './App.vue'
import ZwModule from 'zwplayervue3'
const app = createApp(App)
app.use(ZwModule)
app.mount('#app')
The above code imports the zwplayer module and calls Vue 3’s use method for global registration. After global registration, the player component can be used in any sub-component of the project without separate introduction.
Supported component tag names:
zwplayer(Recommended)zero-web-playerzero-playerZPlayer
Note: This example project uses the local registration method.
Using Composition API (Vue 3.2+)
<script setup>
import { ref } from 'vue'
import { zwplayer } from 'zwplayervue3'
const movieUrl = ref('https://cdn.zwplayer.com/media/VMAP9lxJvRpgn5sP3lV6rQ9qkzQmh5psggso3185.mp4')
const playerOpen = ref(true)
const zwplayerRef = ref(null)
const onPlayerReady = () => {
console.log('player ready event.')
// Get player instance
console.log('播放器实例:', zwplayerRef.value)
}
const onPlayerMediaEvent = (event) => {
console.log('media event:', event.type)
}
</script>
1.3 Component Usage
Basic Usage Example
<template>
<div class="player-container">
<zwplayer
v-if="playerOpen"
ref="zwplayerRef"
nodeid="main-player"
:murl="movieUrl"
@onready="onPlayerReady"
@onmediaevent="onPlayerMediaEvent"
:autoplay="false"
:snapshotButton="true"
:optionButton="true"
:infoButton="true"
:enableDanmu="true"
:chapterButton="true"
:disableMutedConfirm="true"
/>
</div>
</template>
Danmaku Function Example
<template>
<div class="demo">
<zwplayer
v-if="playerOpen"
ref="zwplayerRef"
:murl="movieUrl"
@onready="onPlayerReady"
@onmediaevent="onPlayerMediaEvent"
:autoplay="false"
:sendDanmu="sendDanmu"
:enableDanmu="true"
danmuBarId="danmu-controlbar"
:disableMutedConfirm="true"
/>
<div class="danmubar" id="danmu-controlbar"></div>
</div>
</template>
<script>
export default {
methods: {
sendDanmu(danmuText) {
if (!danmuText) return;
// Parse danmaku data
let danmu;
try {
let jtext = JSON.parse(danmuText);
danmu = {
border: '1px solid #ccc',
text: jtext['text']
};
} catch (e) {
danmu = {
border: '1px solid #ccc',
text: danmuText
};
}
// Add danmaku to player
const player = this.$refs.zwplayerRef;
if (player && player.appendDanmu) {
player.appendDanmu(danmu);
}
}
}
}
</script>
<style scoped>
/* Danmaku control bar style penetration */
.danmubar :deep(.zwp_danmu-controlbar) {
width: 60%;
}
</style>
Logo Watermark Example
<template>
<zwplayer
ref="zwplayerRef"
:murl="movieUrl"
:logo="logo"
:poster="poster"
:autoplay="false"
:disableMutedConfirm="true"
/>
</template>
<script>
export default {
data() {
return {
logo: {
icon: 'https://cdn.zwplayer.com/logo.png',
dock: 'right', // Position: left, right
x: '5%', // Horizontal offset
y: '5%', // Vertical offset
width: '10%', // Width
height: '10%', // Height
opacity: 70 // Opacity 0-100
},
poster: 'https://www.zwplayer.com/zwplayer-preview.png'
};
}
}
</script>
Thumbnail Example
<template>
<zwplayer
ref="zwplayerRef"
:murl="movieUrl"
:thumbnails="thumbnails"
:fluid="true"
/>
</template>
<script>
export default {
data() {
return {
thumbnails: {
url: 'https://cdn.zwplayer.com/media/b44c43c90be3521bc352aad1e80f9cd0_thumb.jpg',
width: 160,
height: 90,
row: 9,
col: 9,
total: 74
}
};
}
}
</script>
Chapter Segmentation Example
<template>
<zwplayer
ref="zwplayerRef"
:murl="movieUrl"
:chapterButton="true"
@onready="onPlayerReady"
/>
</template>
<script>
export default {
methods: {
onPlayerReady() {
const player = this.$refs.zwplayerRef;
const chapters = [{
title: "分段1",
desc: "分段1描述",
time: 0,
duration: 50,
thumb: null
},
{
title: "分段2",
desc: "分段2描述",
time: 50,
duration: 100,
style: {
background: "blue"
},
image: null
},
{
title: "分段3",
desc: "分段3描述",
time: 100,
duration: 200,
style: {
background: "green"
},
image: null
}
];
player.setChapters(chapters);
}
}
}
</script>
1.4 Modified Attributes
The attributes of the zwplayervue3 tag are largely the same as the properties of the native zwplayer constructor parameter object, but zwplayervue3 has adjusted some attributes:
| Attribute Name | Description | Notes |
|---|---|---|
| murl | Media address parameter (can be string, object, or array type). If this attribute changes during runtime, the zwplayervue3 component will automatically call the play method to open the new address. By binding the v-bind attribute, you can dynamically switch playback programs. |
Behavior changed |
| nodeid | Used for the id of the zwplayervue3 component’s top-level parent div. If not provided, the component will automatically generate one. |
Added |
| zwplayerlib | zwplayer library address. zwplayervue3 uses a method of dynamically loading the native zwplayer library at the underlying level, and will not compile the underlying zwplayer library into the project with Vue’s build command. This allows for direct replacement of the zwplayer library file after the project is compiled and published for seamless upgrades, while also optimizing loading speed. This parameter is similar to a CDN address. For example, if zwplayer.js is deployed at http://www.cdn.com/zwplayer/zwplayer.js, set this parameter to that address. This parameter can be omitted; if omitted, the path zwplayer/zwplayer.js in the public directory is used. |
Added |
| danmuBarId | Used to locate the id of the div element for the zwplayer danmaku input control bar. Providing this parameter avoids calling the buildDanmuControlbar function to create a danmaku control bar. Note: The control bar’s class name is zwp_danmu-controlbar. Users can use this class name to further control the style of the danmaku control bar. For example, the CSS below sets the control bar width to 60%:.danmubar :deep(.zwp_danmu-controlbar) { width: 60%;} Note: If defining CSS in <style scoped>, please use Vue’s :deep directive for style penetration. |
Added |
| Other | Please refer to the parameter description of the zwplayer player constructor. The specific attributes to provide depend on the project. |
Common Attributes Description
Display Control Related:
autoplay: Whether to autoplay (boolean, defaultfalse)fluid: Whether to enable fluid layout (boolean, defaultfalse)snapshotButton: Whether to show the snapshot button (boolean)optionButton: Whether to show the option button (boolean)infoButton: Whether to show the info button (boolean)chapterButton: Whether to show the chapter menu button (boolean); does not affect chapter data loading or progress bar markersenableDanmu: Whether to enable danmaku function (boolean)
Media Related:
murl: Media address (string,object, orarray)poster: Poster image address (string)thumbnails: Thumbnail configuration (object)
Function Related:
sendDanmu: Danmaku send callback function (function)disableMutedConfirm: Whether to disable muted confirmation (boolean)keepAudioWindow: Whether to keep audio window (boolean)localPlayback: Whether to play locally (boolean)recordButton: Whether to show record button (boolean)segmentButton: Whether to show segment button (boolean)
1.5 Events
The zwplayervue3 component provides the following events:
| Event Name | Description | Callback Parameters |
|---|---|---|
| onready | Player initialization completed event | None |
| onmediaevent | Media playback event | event object, containing properties like type |
For detailed event descriptions, please refer to the Event Documentation.
Event Usage Example
<template>
<zwplayer
ref="zwplayerRef"
:murl="movieUrl"
@onready="onPlayerReady"
@onmediaevent="onPlayerMediaEvent"
/>
</template>
<script>
export default {
methods: {
onPlayerReady() {
console.log('播放器已就绪');
const player = this.$refs.zwplayerRef;
// Player methods can be called here
},
onPlayerMediaEvent(event) {
console.log('媒体事件:', event.type);
// Common event.type: play, pause, ended, timeupdate, etc.
}
}
}
</script>
1.6 Method Calls
The Vue component of zwplayer provides the same methods as the native zwplayer. To call these methods, obtain the component reference via Vue’s ref attribute.
Obtaining Player Instance
// Method 1: Get in onready event
onPlayerReady() {
const player = this.$refs.zwplayerRef;
console.log('播放器实例:', player);
}
// Method 2: Get directly
const player = this.$refs.zwplayerRef;
Common Method Examples
// Play/Pause
player.play();
player.pause();
// Seek to specified time (seconds)
player.seekTo(30);
// Set volume (0-100)
player.setVolume(50);
// Add danmaku
player.appendDanmu({
border: '1px solid #ccc',
text: '这是一条弹幕',
color: '#ff6b6b'
});
// Set chapters
player.setChapters([{
title: "分段1",
desc: "分段1描述",
time: 0,
duration: 50
}]);
// Get current playback time
const currentTime = player.currentTime();
// Get total video duration
const duration = player.duration();
2. Vue 2.x
2.1 Installation Steps
1. Install Vue Interface Package
You can install the vue2.x interface package for zwplayer using the following command:
npm i zwplayer-vue2x --save
Or install from a local tgz package:
npm install ./zwplayer-vue2x-1.0.32.tgz --save
2. Verify Installation
After successful installation, a zwplayer core library directory will be automatically generated in the project’s public directory. This directory must be built and published along with the project.
3. Version Requirements
- Vue 2.6+
- Supports Vue CLI 4.x/5.x
2.2 Main Differences from Vue 3
The usage of the Vue 2.x version is basically the same as the Vue 3.x version, with the main differences being:
| Difference | Vue 2.x | Vue 3.x |
|---|---|---|
| Package Name | zwplayer-vue2x |
zwplayervue3 |
| Global Property Config | Vue.prototype.$xxx |
app.config.globalProperties.$xxx |
| Style Penetration | /deep/ or ::v-deep |
:deep() |
| Composition API | ❌ Not supported | ✅ Supported |
| Build Tools | Vue CLI (Webpack) | Vite or Webpack |
Note: Component attributes, events, and method calling methods are identical.
2.3 Component Registration and Usage
Local Registration (Recommended)
import { zwplayer } from 'zwplayer-vue2x'
export default {
name: 'zwplayer-demo',
components: {
zwplayer // Local registration component
},
data() {
return {
movieUrl: 'https://cdn.zwplayer.com/media/VMAP9lxJvRpgn5sP3lV6rQ9qkzQmh5psggso3185.mp4',
playerOpen: true,
player: null
};
},
methods: {
onPlayerReady() {
console.log('player ready event.');
this.player = this.$refs.zwplayerRef;
},
onPlayerMediaEvent(event) {
console.log('media event:', event.type);
}
}
}
2.5 Style Penetration
In Vue 2.x, use /deep/ or ::v-deep for style penetration:
/* Method 1: Use /deep/ */
.danmubar /deep/ .zwp_danmu-controlbar {
width: 60%;
}
/* Method 2: Use ::v-deep */
.danmubar ::v-deep .zwp_danmu-controlbar {
width: 60%;
}
2.5 Complete Example
<template>
<div class="demo-page">
<zwplayer
v-if="playerOpen"
ref="zwplayerRef"
:murl="movieUrl"
@onready="onPlayerReady"
@onmediaevent="onPlayerMediaEvent"
:autoplay="false"
:snapshotButton="true"
:optionButton="true"
:infoButton="true"
:enableDanmu="true"
:chapterButton="true"
:disableMutedConfirm="true"
:fluid="true"
danmuBar="danmu-controlbar"
/>
</div>
</template>
<script>
import { zwplayer } from 'zwplayer-vue2x'
export default {
name: 'zw-basic',
components: {
zwplayer
},
data() {
return {
movieUrl: 'https://cdn.zwplayer.com/media/VMAP9lxJvRpgn5sP3lV6rQ9qkzQmh5psggso3185.mp4',
playerOpen: true
};
},
methods: {
onPlayerReady() {
console.log('player ready event.');
const player = this.$refs.zwplayerRef;
// Call player methods
},
onPlayerMediaEvent(event) {
console.log('media event:', event.type);
}
}
}
</script>
<style scoped>
.danmubar /deep/ .zwp_danmu-controlbar {
width: 60%;
}
</style>
2.6 Component Attributes and Methods
The component attributes, events, and methods of the Vue 2.x version are completely consistent with the Vue 3.x version. For details, see the relevant descriptions for Vue 3.x above:
- Component attributes: See 1.4 变动属性
- Event descriptions: See 1.5 事件
- Method calls: See 1.6 方法调用
- More examples: See various examples in 1.3 组件使用
3. Example Repositories
3.1 Vue 3.x Examples
- Gitee: https://gitee.com/chenfanyu/zwplayervue3-demo
- GitHub: https://github.com/chenfanyu/zwplayervue3-demo
3.2 Vue 2.x Examples
- Gitee: https://gitee.com/chenfanyu/zwplayer-vue2x-demo
- GitHub: https://github.com/chenfanyu/zwplayer-vue2x-demo
4. Notes
4.1 Project Configuration
- Directory Structure: Ensure a
publicdirectory exists in the project before installation. - Core Library: The
public/zwplayerdirectory must be published along with the project. - Dynamic Loading:
zwplayeruses a dynamic loading mechanism that supports seamless upgrades and will not be packaged into the final bundle. - Method Calls: Call player methods via
refreferences.
4.2 Best Practices
-
Use v-if to Control Display
<zwplayer v-if="playerOpen" ref="zwplayerRef" :murl="movieUrl" />Using
v-ifinstead ofv-showensures the player is initialized and destroyed correctly. -
Wait for Player Ready Before Calling Methods
onPlayerReady() { const player = this.$refs.zwplayerRef; // Methods can only be called after player is ready player.play(); } -
Style Penetration
When modifying internal player styles, style penetration is required:
Vue 3.x:
/* Modify danmaku control bar width in scoped styles */ .danmubar :deep(.zwp_danmu-controlbar) { width: 60%; }Vue 2.x:
/* Use /deep/ or ::v-deep */ .danmubar /deep/ .zwp_danmu-controlbar { width: 60%; } /* Or */ .danmubar ::v-deep .zwp_danmu-controlbar { width: 60%; } -
Responsive Layout
.player-container { width: 100%; max-width: 1280px; margin: 0 auto; } @media (max-width: 768px) { .player-container { width: 100%; height: auto; aspect-ratio: 16/9; } }
4.3 Common Questions
Q: Why is the player not displaying?
A: Check the following points:
- Ensure
v-ifis used instead ofv-show. - Ensure the media URL is accessible.
- Check the browser console for error messages.
- Confirm the
public/zwplayerdirectory exists and contains required files.
Q: How to dynamically switch videos?
A: Directly modify the value of the murl attribute, and the component will automatically reload:
this.movieUrl = 'new-video-url.mp4';
Q: How to customize danmaku control bar styles?
A: Use CSS style penetration.
Vue 3.x:
.danmubar :deep(.zwp_danmu-controlbar) {
width: 60%;
background-color: #232323;
}
Vue 2.x:
.danmubar /deep/ .zwp_danmu-controlbar {
width: 60%;
background-color: #232323;
}
Q: How to get the current status of the player?
A: Call the corresponding methods after obtaining the player instance via ref:
const player = this.$refs.zwplayerRef;
const currentTime = player.currentTime();
const duration = player.duration();
const isPlaying = player.isPlaying(); // If this method exists
4.4 Project Structure Recommendations
Vue 3.x Project Structure (Vite):
your-vue3-project/
├── public/
│ └── zwplayer/ # Player core library (auto-generated, must be published)
├── src/
│ ├── components/
│ │ └── Player.vue # Player wrapper component
│ ├── views/
│ │ └── VideoPage.vue # Page using the player
│ ├── App.vue
│ └── main.js
├── package.json
└── vite.config.js
Vue 2.x Project Structure (Vue CLI):
your-vue2-project/
├── public/
│ └── zwplayer/ # Player core library (auto-generated, must be published)
├── src/
│ ├── components/
│ │ └── Player.vue # Player wrapper component
│ ├── views/
│ │ └── VideoPage.vue # Page using the player
│ ├── App.vue
│ └── main.js
├── package.json
└── vue.config.js
4.5 Debugging Suggestions
-
Enable Development Mode Logging
onPlayerReady() { console.log('播放器已就绪:', this.$refs.zwplayerRef); } -
Listen to All Media Events
onPlayerMediaEvent(event) { console.log('媒体事件:', event.type, event); } -
Use Browser Developer Tools
- Check network requests to confirm
zwplayer.jsloads correctly. - Check the console for error messages.
- Use the element inspector to view the DOM structure.
- Check network requests to confirm
4.6 Performance Optimization
- Lazy Loading: For non-above-the-fold players, use
v-iffor lazy loading. - Destroy Instances: Ensure the player instance is properly cleaned up when the component is destroyed.
- Resource Preloading: Consider preloading for key videos.
- CDN Acceleration: Deploy the
zwplayercore library to a CDN and specify it using thezwplayerlibattribute.
5. Changelog
Vue 3.x (zwplayervue3)
- v1.0.33: Optimized Vue 3 compatibility, supports Composition API.
- v1.0.30: Added thumbnails, chapters, danmaku, and other features.
- v1.0.20: Initial version, supports basic playback functions.
Vue 2.x (zwplayer-vue2x)
- v1.0.32: Optimized Vue 2 compatibility, fixed known issues.
- v1.0.30: Added thumbnails, chapters, danmaku, and other features.
- v1.0.20: Initial version, supports basic playback functions.