首页 > 解决方案 > 让组件对状态中的数据变化做出反应

问题描述

我的 vue 应用程序的布局如下:

应用程序.vue

<template>
  <div id="app">
    <Progress />
    <router-view />
    <Footer />
  </div>
</template>
<script>
import Footer from "@/components/Footer";
import Progress from "@/components/Progress";

export default {
  components: {
    Footer,
    Progress,
  },
};
</script>
进度条的代码片段:

<template>
  <section>
    <div class="columns is-mobile pt-6" v-show="progressBar()">
      <div class="column is-three-fifths is-offset-one-fifth">
        <progress
          class="progress is-success"
          :value="(progress.count / 9) * 100"
          max="100"
          >{{ (progress.count / 9) * 100 }} %</progress
        >
      </div>
    </div>
  </section>
</template>
<script>
import { mapGetters } from "vuex";
export default {
  name: "Progress",
  methods: {
    progressBar() {
      console.log(this.progress.status);
      if (this.progress.status == false) {
        return false;
      }
      return true;
    },
  },
  computed: mapGetters({
    progress: "getProgressBar",
  }),
};
</script>

以及进度条的 vuex 存储。

src/store/modules/ProgressBar.js

const state = {
  count: 1,
  status: false,  
};

const getters = {
  getProgressBar: state => state,
};

const actions = {
};

const mutations = {
  setProgressBar(state, value) {
    state.status = value;
  },
  progressIncrease(state) {
    state.status = state.status + 1;
    console.log(state.status);
  }
};

export default {
  state,
  getters,
  actions,
  mutations,
};
还有我的路由组件Basics.vue从路由加载/basic

<template>
  /* code for form layout goes here*/
</template>
<script>
export default {
  name: "Basics",
  methods: {
    toNetworks() {
      this.$router.push({ name: "Location" });
      this.$store.commit("progressIncrease");
    },
    /* other codes to handel input */
  },
  created(){
    this.$store.commit("setProgressBar", true);
  }
};
</script>

使用上面的代码,我试图count根据表单步骤增加状态中的变量并根据计算显示进度条。

状态设置正确,我可以通过提交来增加它。但是进度条组件对状态中的更新数据没有反应。

我知道当组件加载到组件中时,该mapGetter方法只调用一次。<Progress/>App.vue

是否有任何方法/方式可以对<Progress/>路由器组件对状态中数据的更改做出反应?

标签: javascriptvue.jsvuejs2vuex

解决方案


在您的 progressIncrease 突变中,您正在增加错误的状态(状态 - 这是一个布尔值)。您将需要两个吸气剂。另外,我认为您的吸气剂应该返回状态和计数状态。你应该有

const mutations = {
  progressIncrease(state) {
    state.count = state.count + 1;
  }
};

const getters = {
  count: state => {
    return state.count;
  },
  status: state => {
    return state.status;
  }
}

在组件中,可以使用 mapGetters 如下

computed: {
  ...mapGetters([
    'count',
    'status',
  ])
}

您可以将“this.status”替换this.progress.status为“this.progress.count”,将“this.progress.count”替换为“this.count”。如果你愿意,你也可以使用别名。您可以在此处查看有关 getter的更多信息

但是,最好的做法是使用 mapState,因为您要返回状态,而不是像上面链接的 vue 文档示例中那样更改它。

那会变成

 computed: mapState({
    count: state => state.count,
    status: state => state.status,
 })
 

您现在可以将状态称为this.countthis.status。同样,如果您愿意,您可以使用别名。您可以在此处了解有关 mapState 的更多信息


推荐阅读