[Vuejs]-How to call $emit in Pinia's $onAction callback using Options API?

2👍

In the code you provided, it seems like you’re using the Composition API in a Vue 3 component. However, there are a few issues with your code:

  1. The this context inside the arrow function passed to $onAction is undefined. Arrow functions do not have their own this, so you can’t use this inside them to refer to the Vue component instance.

  2. Vue 3’s Composition API does not use this to access component properties or methods. Instead, you should directly reference someStore if it contains the logic you need.

If you want to emit an event from your component when an action in someStore is triggered, you should use the Composition API’s watch function to watch for changes in someStore. Here’s an example of how you can do this:

export default {
  setup() {
    const someStore = useSomeStore();

    // Watch for changes in someStore
    watch(() => someStore.someProperty, (newValue, oldValue) => {
      // Perform actions here and emit events if needed
      // You can access component properties directly without "this"
    });

    return { someStore };
  },
}

In this example, you should replace someProperty with the actual property or state you want to watch in someStore. When that property changes, the callback function provided to watch will be executed, allowing you to perform actions and emit events as necessary.

Using watch is a more appropriate way to respond to changes in reactive data when using the Composition API in Vue 3.

👤Haru

Leave a comment