vue.jsvue-componentpusherpusher-js

PusherJS and Vue 3?


I want to watch pusher events and update the local state or rerender component.

My current way to follow pusher notification.

...
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();
  },

Please help me, have a nice day.


Solution

  • You are losing your this scope in the my-event handler. You should be using a fat arrow function instead of a normal function:

    ...
    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();
      },
    

    Here's a great article that goes more into depth about this scope and fat arrow functions: https://www.freecodecamp.org/news/learn-es6-the-dope-way-part-ii-arrow-functions-and-the-this-keyword-381ac7a32881/