vue.js - 在 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 2 构建的pusher-vue
,vue-pusher
因此您需要使用 Vue 3迁移构建来使库在您的项目中工作。
要设置您的 Vue CLI 脚手架项目:
安装与您的 Vue 构建版本匹配的 Vue 兼容性构建和 SFC 编译器(即,安装
@vue/compat@^3.1.0
并且@vue/compiler-sfc@^3.1.0
如果您有vue@^3.1.0
)package.json
:npm i -S @vue/compat@^3.1.0 npm i -S @vue/compiler-sfc@^3.1.0
将 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
1.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')
推荐阅读
- sql - SQL 子查询和 RANK()
- matlab - MATLAB:将 cellfun 与多级元胞数组一起使用
- php - PHP - if 子句后的“:”有什么用?
- botframework - 在 boframework 中发送自适应卡后自定义/删除它
- php - 无法使用href删除codeigniter中的记录
- c# - 我的数据绑定怎么会写出 Length 属性?
- javascript - 如何使用 jquery 替换 kendoDropDownList 文本?
- python - gensim - Doc2Vec:差异迭代与时代
- r - 使用 group by 和 tidy 运行多个模型并将结果提取到数据框
- java - 如何用最少的代码使 JOptionPane 不可见