首页 > 解决方案 > Vuex 状态更改不会触发页面上的反应

问题描述

我正在使用 vue 制作验证码组件。我尝试在创建组件时获取验证码。当我以异步方式执行此操作时,尽管状态已经更新,但页面不会是反应式的。但是我以同步的方式进行操作时,一切都很好。所以,我想知道为什么异步方式不起作用?

这有效

<template>
  <section>
    <div class="captcha-container">
      <div v-if="captcha" v-html="captcha.data"></div>
    </div>
  </section>
</template>

<script>
import { mapState, mapActions } from "Vuex";

export default {
  created: function() {
    this.$store.commit('setCaptcha', {id: 'xx', data:'Hi'});
  },
  computed: {
    ...mapState(["captcha"])
  },
};
</script>

这不起作用

<template>
  <section>
    <div class="captcha-container">
      <div v-if="captcha" v-html="captcha.data"></div>
    </div>
  </section>
</template>

<script>
import { mapState, mapActions } from "Vuex";

export default {
  created: function() {
    setTimeout(() => {
      this.$store.commit('setCaptcha', {id: 'xx', data:'Hi'});
    }, 1000);
  },
  computed: {
    ...mapState(["captcha"])
  },
};
</script>

标签: asynchronousvuejs2vuex

解决方案


推荐阅读