首页 > 解决方案 > vuex 状态不是反应式的

问题描述

我正在使用 vuex 进行加载微调器条件以处理loading = true/false多个组件。

LoadingSpinner.vue

<template>
  <fulfilling-square-spinner
    v-show="loading"
    class="loading-spinner"
    :animation-duration="4000"
    :size="50"
    color="#007bff"
  />
</template>

<script>
import { FulfillingSquareSpinner } from 'epic-spinners';
import { mapState } from 'vuex';
export default {
  components: {
    FulfillingSquareSpinner
  },
  computed: {
    ...mapState({}),
    loading: function() {
      return this.$store.state.isloading;
    }
  },
}
</script>

<style lang="scss" scoped>
  .loading-spinner {
    z-index: 1;
    position: absolute;
    top: 315px;
    left: 0;
    right: 0;
    margin: auto;
  }
</style>

我正在使用一个名为Epic Spinners的第三方加载微调器 ,我将其封装起来以在其他几个组件上提供相同的样式和定位。

这就是我的 LoadingSpinner 商店的样子:

const state = {
  data() {
    return {
      isLoading: false
    }
  },
};
const getters = {};
const actions = {};
const mutations = {
  loading(state, isLoading) {
    console.log({isLoading})
    if (isLoading) {
      state.isLoading = true;
    } else {
      state.isLoading = false;
    }
  }
};
export default {
  state,
  getters,
  actions,
  mutations,
};

我想在 axios 调用开始之前将微调器切换为 true,并在 axios 完成后切换回 false。

this.$store.commit('loading', true);
or 
this.$store.commit('loading', false);

现在的问题是,微调器没有反应,不会切换为真或假。我在LoadingSpinner.vue' isundefined` 中定义的计算属性。

标签: javascriptvue.jsvuex

解决方案


我不确定你什么时候使用mapState,那么你为什么要通过$store.

computed: {
  ...mapState(['isLoading'])
  // You can access `isLoading` as a property of `this` ex - this.isLoading

}

现在您可以简单地使用响应属性。

<template>
  <fulfilling-square-spinner
    v-show="isLoading"
    class="loading-spinner"
    :animation-duration="4000"
    :size="50"
    color="#007bff"
  />
</template>

你也可以mapMutations使用mutations

methods: {
  ...mapMutations(['loading'])
  // it's get mapped as this.$store.commit('loading') and you can use as a property of this

  // this.loading()
}

推荐阅读