UNPKG

tcplayer-plugin

Version:

基于腾讯云播放器的组件库,支持Vue2、Vue3和原生JS

99 lines (85 loc) 2.56 kB
import TcPlayer from './tcplayer.vue'; import './utils'; import { version } from './version.js'; // 检测Vue版本 const isVue2 = (vue) => vue && !!vue.prototype; const isVue3 = (vue) => vue && !!vue.config && !!vue.config.globalProperties; // Vue2和Vue3兼容安装函数 const install = function(app, options = {}) { if (isVue2(app)) { // Vue 2安装方式 app.component(TcPlayer.name, TcPlayer); } else if (isVue3(app)) { // Vue 3安装方式 app.component(TcPlayer.name, TcPlayer); } else { console.error('[TcPlayer] 不支持的Vue版本,请使用Vue 2.x或3.x'); } }; // 为Vue2创建一个具有install方法的对象 TcPlayer.install = install; // 自动安装(当通过script标签引入时) if (typeof window !== 'undefined' && window.Vue) { if (isVue2(window.Vue)) { window.Vue.use(TcPlayer); } else if (isVue3(window.Vue)) { window.Vue.use({ install }); } } // 原生JS用法 class TcPlayerJS { constructor(element, options) { if (typeof element === 'string') { element = document.querySelector(element); } if (!element) { throw new Error('[TcPlayer] 目标DOM元素不存在'); } this.element = element; this.options = options || {}; this._init(); } _init() { // 将Vue组件渲染到目标元素 const container = document.createElement('div'); container.className = 'tc-player-container'; this.element.appendChild(container); // 这里使用运行时API创建组件实例 if (window.Vue) { if (isVue3(window.Vue)) { const app = window.Vue.createApp({ render: () => window.Vue.h(TcPlayer, { props: this.options }) }); this.instance = app.mount(container); } else if (isVue2(window.Vue)) { const VueConstructor = window.Vue; const Component = VueConstructor.extend({ render: (h) => h(TcPlayer, { props: this.options }) }); this.instance = new Component().$mount(container); } } else { console.error('[TcPlayer] 请先引入Vue.js'); } } destroy() { if (this.instance && this.instance.$destroy) { this.instance.$destroy(); } if (this.element) { this.element.innerHTML = ''; } } } // 导出 export { TcPlayer, TcPlayerJS, install, version }; // 默认导出一个具有Vue插件格式的对象 const plugin = { install, version, TcPlayer, TcPlayerJS }; // 确保为Vue2提供一个可用的install方法 plugin.install = install; export default plugin;