首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PusherJS和Vue 3?

PusherJS和Vue 3?
EN

Stack Overflow用户
提问于 2021-11-18 21:48:09
回答 1查看 37关注 0票数 0

我想观看pusher事件并更新本地状态或rerender组件。

我目前关注pusher通知的方式。

代码语言:javascript
复制
...
methods: {
    refreshSlider() {
      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 () {
        // alert("1");
        console.log(this.sliders); //undefined!
      });
    },
  },
...
async mounted() {
    .....
    this.refreshSlider();
  },

请帮帮我,祝你有愉快的一天。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-18 22:23:24

您正在丢失my-event处理程序中的this作用域。您应该使用胖箭头函数,而不是普通函数:

代码语言:javascript
复制
...
methods: {
    refreshSlider() {
      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 () => {
        // alert("1");
        console.log(this.sliders); //should exist now
      });
    },
  },
...
async mounted() {
    .....
    this.refreshSlider();
  },

这里有一篇很棒的文章,它更深入地介绍了this作用域和胖箭头函数:https://www.freecodecamp.org/news/learn-es6-the-dope-way-part-ii-arrow-functions-and-the-this-keyword-381ac7a32881/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70027159

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档