首页 > 解决方案 > 在 Vue3 上配置 Pusher

问题描述

我在 Vue3 中有一个项目,想实现一个实时 API 或 Web 套接字。所以我尝试使用 Vue 第三方库pusher-vue 和 vue-pusher 来使用 pusher。使用pusher-vue我收到错误:Uncaught TypeError: e.prototype is undefined。使用vue-pusher我收到错误:Uncaught TypeError: Vue.prototype is undefined。以下是库的配置:

推动者

组件.vue

export default{
  channels: {
       applications_channel: {
           subscribeOnMount: true,
           subscribed(){
               console.log("Some text")
           },

           bind:{
               add_application_event(data){
                   console.log(data)
               }
           }
       }
  }
}

main.js

createApp(App)
.use(PusherVue, {
    app_key: "MY_KEY",
    cluster: 'MY_CLUSTER',
    debug: true,
    debugLevel: "all"
})
.mount("#app")

推动者

组件.vue

export default{
  read(){
      var channel = this.$pusher.subscribe('applications-channel')

            channel.bind('add-application-event', ({ log }) => {
                console.log(log);
            })
       }
}

main.js

createApp(App)
.use(require("vue-pusher"), {
    api_key: "MY_KEY",
    options: {
        cluster: 'MY_CLUSTER',
        ecrypted: true,
    }
})
.mount("#app")

请您帮助我如何在 Vue3 上配置它或推荐任何适合初学者的替代方案以在 Vue3 上实现相同的功能。

标签: vue.jswebsocketreal-timevuejs3pusher

解决方案


两者都是为 Vue 2 构建的pusher-vuevue-pusher因此您需要使用 Vue 3迁移构建来使库在您的项目中工作。

要设置您的 Vue CLI 脚手架项目:

  1. 安装与您的 Vue 构建版本匹配的 Vue 兼容性构​​建和 SFC 编译器(即,安装@vue/compat@^3.1.0并且@vue/compiler-sfc@^3.1.0如果您有vue@^3.1.0package.json

    npm i -S @vue/compat@^3.1.0
    npm i -S @vue/compiler-sfc@^3.1.0
    
  2. 将 Webpack 配置为 build 的别名vue@vue/compat并将vue-loader的兼容模式设置为 Vue 2:

    // vue.config.js
    module.exports = {
      chainWebpack: config => {
        config.resolve.alias.set('vue', '@vue/compat')
    
        config.module
          .rule('vue')
          .use('vue-loader')
          .tap(options => {
            return {
              ...options,
              compilerOptions: {
                compatConfig: {
                  MODE: 2
                }
              }
            }
          })
      }
    }
    

演示:vue-pusher在带有迁移构建的 Vue 3 中

但是,vue-pusher1.1.0 似乎只在 Vue 实例上公开了一个新的 Pusher 实例(来自pusher-js) 。this.$pusher该代码可以作为插件轻松迁移到 Vue 3:

// plugins/pusher.js
export default (app, { apiKey, ...options }) => {
  const Pusher = require('pusher-js')
  app.config.globalProperties.$pusher = new Pusher(apiKey, options)
}

// main.js
const { createApp } = require('vue')
import App from './App.vue'
import PusherPlugin from './plugins/pusher'

createApp(App)
  .use(PusherPlugin, { apiKey: 'YOUR_API_KEY', cluster: 'YOUR_CLUSTER' })
  .mount('#app')

演示:pusher-js在 Vue 3 中


推荐阅读