Home > database >  Vuex state updates in updated life cycle hook
Vuex state updates in updated life cycle hook

Time:04-12

Hi I am using Vuex in Nuxt.

If I comment h2 and click on click button, lifecycle hook updated() does not run even when the store variable counter changes in it.

If I uncomment the h2 line updated() lifecycle hook runs on every click.

How can I get the updated changes from store counter in component without using it in template.

<template>
  <div>
    <!-- <h2>{{ counter }}</h2> -->
    <button @click="onSubmit">click</button>
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'

const { mapState } = createNamespacedHelpers('profile')

export default {
  name: 'App',
  methods: {
    onSubmit() {
      console.log('clicked')
      this.$store.commit('profile/increment', 1)
    },
  },
  computed: {
    ...mapState(['counter']),
  },
  created() {
    console.log('created', this.$store.state.profile.counter)
  },
  updated() {
    console.log('updated', this.$store.state.profile.counter)
    console.log('updated', this.counter)
  },
}
</script>

Store

export const state = () => ({
  counter: 0,
})

export const mutations = {
  increment(state) {
    state.counter  
  },
}

CodePudding user response:

updated() hook is called when vue decides to rerender the component. So if your template doesn't use the counter value, there is no need for rerender and that's why updated() is not called.

If you want to run some code whenever the counter is updated, you need a watcher:

watch: {
  '$store.state.profile.counter'(val) {
    console.log(`The counter was updated. New value is ${val}`)
  }
}
  • Related