【问题标题】:Vuex 4 modules not working when refactoring modules to seprate files将模块重构为单独的文件时,Vuex 4模块不起作用
【发布时间】:2021-11-28 10:45:39
【问题描述】:

我一直在学习 vuex4,在那里我在 main.js 中编写了所有状态、动作、getter...

现在我已经了解了模块,并尝试将我的代码重构为单独文件中的模块。一切正常,除了一个 v-for 循环,其中数字应该出现但不出现。当应用程序上的“历史”下的数字发生变化时,该数字应该会出现。

我正在使用 counter.js 中的突变“addToCounter”和“minToCounter”更新历史数组

History.vue(这是 v-for 循环不起作用的地方)

  <div class="container">
    <h4>History</h4>
    <div class="flex">
      <p
        v-for="(number,index) in history"
        :key="index"
        :class="activeIndexes(parseInt(value)).includes(index) && 'bold'"
      >
       {{number}}
      </p>
    </div>
    <input
      type="text"
      placeholder="search by index"
      v-model="value"
    >
  </div>
</template>

<script>
import {mapState, mapGetters} from "vuex";

export default {
  data(){
    return{
      value: 0,
    }
  },
  computed: {
    ...mapState(['history']),
    ...mapGetters(['activeIndexes']),
  }
}
</script>

<style>...</style>

counter.js(模块保存在modules/counter.js中)

import axios from "axios";

const state = {
        counter: 0,
        history: [0],
};
const mutations = {
    addToCounter(state, payload){
        state.counter = state.counter + payload;
        state.history.push(state.counter)
    },
    minToCounter(state, payload){
        state.counter = state.counter - payload;
        state.history.push(state.counter)
    }
};
const actions = {
    //async je takrt k zahtevamo nek http request npr od api-ja spodnji primer:
    async addRandomNumber(context) {
        let data = await axios.get('https://www.random.org/integers/?num=1&min=-1000&max=1000&col=1&base=10&format=plain&rnd=new');
        context.commit("addToCounter",data.data);
    }
};
const getters = {
    activeIndexes: (state) => (payload) => {
        let indexes = [];
        state.history.forEach((number, index) => {
            if(number === payload) {
                indexes.push(index)
            }
        });
        return indexes
    }
};

export default {
    state,mutations,actions,getters
}

main.js

import { createApp } from 'vue'
import { createStore } from 'vuex';
import counter from "./modules/counter";

import App from './App.vue'

const store = createStore({
    modules: {
        counter: counter,
    }
})

createApp(App).use(store).mount('#app')

【问题讨论】:

  • 你在你的开发者工具中看到状态是否更新了吗?
  • @JonathanAkweteyOkine 是的。 prnt.sc/1vbprhw(所有这些数字都应显示在历史记录下)

标签: javascript vue.js vuex-modules vuex4


【解决方案1】:

想通了:)。

在 History.vue 中

我变了:

computed: {
…mapState([‘history’]), → …mapState([‘counter’]) //as module name is counter
…mapGetters([‘activeIndexes’]),
}

然后为 v-for

v-for="(number,index) in history" → v-for="(number,index) in counter.history"

【讨论】:

    猜你喜欢
    • 2019-04-26
    • 2020-08-21
    • 2015-12-13
    • 2019-07-22
    • 2019-10-19
    • 2020-05-30
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    相关资源
    最近更新 更多