You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中使用PusherJS监听事件无法访问组件this实例问题求助

问题根因

你遇到的this指向异常是普通函数的绑定规则导致的:Pusher触发事件回调时,普通function定义的回调内部this指向的是Pusher的channel实例/全局对象,并非Vue组件实例,因此无法访问到组件上定义的sliders等属性。

解决方案

以下三种方案任选一种即可解决问题:

  • 方案1:使用箭头函数定义回调(最常用,代码最简洁)
    箭头函数的this继承自外层作用域,此处外层refreshSlider方法的this就是Vue组件实例,因此可以正常访问组件属性。
    修改后的代码如下:
channel.bind("my-event", async () => {
  console.log(this.sliders); // 可正常访问
  // 此处编写更新组件状态、触发重渲染的逻辑即可
});
  • 方案2:提前缓存组件实例
    在回调外层将组件this存入临时变量,回调内部用临时变量访问组件属性:
refreshSlider() {
  const vm = this; // 缓存组件实例
  const pusher = new Pusher(process.env.VUE_APP_PUSHER_ID, {
    cluster: "eu",
  });
  Pusher.logToConsole = true;
  const channel = pusher.subscribe("my-channel");
  channel.bind("my-event", async function () {
    console.log(vm.sliders); // 用缓存的实例访问属性
  });
},
  • 方案3:手动绑定this到组件实例
    用Function.prototype.bind方法强制指定回调的this指向为组件实例:
channel.bind("my-event", async function () {
  console.log(this.sliders);
}.bind(this));
额外优化建议

建议你将pusher实例、channel实例挂载到组件属性上,在组件销毁前解绑事件、取消订阅、断开连接,避免内存泄漏:

data() {
  return {
    pusherInstance: null,
    pusherChannel: null,
    sliders: [] // 你的原有业务属性
  }
},
methods: {
  refreshSlider() {
    this.pusherInstance = new Pusher(process.env.VUE_APP_PUSHER_ID, {
      cluster: "eu",
    });
    Pusher.logToConsole = true;
    this.pusherChannel = this.pusherInstance.subscribe("my-channel");
    this.pusherChannel.bind("my-event", async () => {
      // 你的业务逻辑
    });
  }
},
// Vue2 用 beforeDestroy 钩子,Vue3 用 beforeUnmount 钩子
beforeDestroy() {
  if (this.pusherChannel) {
    this.pusherChannel.unbind("my-event");
    this.pusherInstance.unsubscribe("my-channel");
    this.pusherInstance.disconnect();
  }
},
async mounted() {
  this.refreshSlider();
}

内容的提问来源于stack exchange,提问作者Milos N.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 18:15:02