Reference Vue store from Capacitor listener

Hello,

I have a Vue js app and I am using a Capacitor plugin to capture an event in the application - “appUrlOpen” by defining a listener.
This works well and is defined as below : -

In my User.vue

<script>
import { Plugins } from "@capacitor/core";
const { App } = Plugins;
.
.
beforeCreate() {
    if (isPlatform("hybrid")) {
      App.addListener("appUrlOpen", function (data) {
        console.log("Inside listener works well : " + data.url);
        this.$store.dispatch("setUrl", data.url);
      });

    }

  },
.
.
</script>

Now the problem is I am not able to get hold of the $store as it is always undefined, which means my ‘this’ is not referencing to my Vue app.

How can I update the values in the Vue store from within the listener function ?

Thank you.

Try switching your listener function to an arrow function:

beforeCreate() {
    if (isPlatform("hybrid")) {
      App.addListener("appUrlOpen", (data) => {
        console.log("Inside listener works well : " + data.url);
        this.$store.dispatch("setUrl", data.url);
      });
    }
  },

Or store this in a const before adding the listener, and use the const to reference $store.

beforeCreate() {
    if (isPlatform("hybrid")) {
      const vueThis = this;
      App.addListener("appUrlOpen", function(data) {
        console.log("Inside listener works well : " + data.url);
        vueThis.$store.dispatch("setUrl", data.url);
      });
    }
  },

The arrow function did the trick. Surprisingly it didn’t work the first time.
Thank you @dolthead

1 Like