更新生命周期钩子中的 Vuex 状态更新

Vuex state updates in updated life cycle hook

您好,我在 Nuxt 中使用 Vuex。

如果我评论 h2 并点击点击按钮,生命周期挂钩 updated() 不会 运行 即使其中的存储变量计数器发生变化。

如果我在每次点击时取消注释 h2 行 updated() 生命周期挂钩 运行s。

如何在不在模板中使用的情况下从组件中的商店计数器获取更新的更改。

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

商店

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

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

updated() hook 在 vue 决定重新渲染组件时被调用。因此,如果您的模板不使用计数器值,则无需重新渲染,这就是不调用 updated() 的原因。

如果您想在计数器更新时运行一些代码,您需要一个观察者:

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