Home > Net >  Watch/Subscribe if certain action has occurred in store
Watch/Subscribe if certain action has occurred in store

Time:04-09

How do you watch or subscribe to an action occurring in a store?

I tried adding a watch (see below) however this doesn't work.

setShowModal is the action I want to watch/subscribe to in my component)

Component:

<script lang="ts">
import { defineComponent } from 'vue'
import { store } from '@/stores/store'

export default defineComponent({
    data () {
        return {
            showModal: store().showModal
        }
    },
    watch: {
        showModal(oldValue, newValue) {
            if (newValue) {
                this.getComments()
            }
        }
    },

Store:

state: () => {
    return {
      showModal: false
    }
},
actions: {
  setShowModal(val: boolean) {
    this.showModal = val
  }
}

The only way I have gotten the watch to fire (only when value gets changed to false) is if I write my component like this:

<script lang="ts">
import { defineComponent } from 'vue'
import {store} from '@/stores/store'

export default defineComponent({
    data () {
        return {
            store: store()
        }
    },
    watch: {
        'store.showModal': function(newValue) {
            if (newValue) {
                this.getComments()
            }
        }
    },

CodePudding user response:

data () {
    return {
        store: store()
    }
},
watch: {
    'store.showModal': function(newValue) {
        if (newValue) {
            this.getComments()
        }
    }
},

CodePudding user response:

How to get reactive state from Pinia store in Vue2.

import { mapState } from 'pinia'
import {store} from '@/stores/store'

export default {
  computed: {
    // gives access to this.showModal inside the component
    // which you can then watch
    ...mapState(store, ['showModal '])
  },

  watch: {
    showModal(newVal) {
      this.getComments();
    }
  },
}

Worth noting that state mapped in this way is readonly. Read the docs further if you want the writable state (which in this case, you do not want).

  • Related