【问题标题】:PusherJS and Vue 3?Pusher JS 和 Vue 3?
【发布时间】:2021-12-29 18:35:19
【问题描述】:

我想观看推送事件并更新本地状态或重新渲染组件。

我目前关注推送通知的方式。

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

请帮助我,祝你有美好的一天。

【问题讨论】:

    标签: vue.js vue-component pusher pusher-js


    【解决方案1】:

    您在my-event 处理程序中丢失了this 范围。您应该使用粗箭头函数而不是普通函数:

    ...
    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/

    【讨论】:

      猜你喜欢
      • 2020-06-14
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 2022-10-21
      • 2021-11-23
      相关资源
      最近更新 更多