vue.js使用compositeApi和sfc在vuex中观察数组状态的变化



我正在努力观察vuex中状态的变化。状态是一个数组。我只需按下一个按钮就可以更改该数组的值。每当我按下这个按钮,数组(vuex状态(发生变化时,我都想在屏幕上的列表中显示这些值。

这是主要的vuex商店:

import { createStore } from 'vuex';
import rollingModule from './modules/rolling/index.js';
const store = createStore({
modules: {
rolling: rollingModule,
},
});
export default store;

这是我的vuex存储模块:

export default {
namespaced: true,
state() {
return {
numbers: [0, 0, 0, 0, 0],
};
},
mutations: {
rollDice(state, payload) {
state.numbers = payload;
},
},
actions: {
rollDice(context) {
const rolledNumbers = [];
for (let i = 0; i < 5; i++) {
rolledNumbers.push(Math.floor(Math.random() * 7));
}
context.commit('rollDice', rolledNumbers);
},
},
getters: {
getNumbers: (state) => state.numbers,
},
};

我的第一次尝试是使用计算属性来对更改做出反应,但这似乎不起作用。然后,我为该计算属性添加了一个观察程序,以console.log旧值和新值,但该观察程序似乎从未被解雇。

这是我的组件代码:

<template>
<ul>
<li v-for="number in rolledNumbers" :key="number">
{{ number }}
</li>
</ul>
</template>
<script setup>
import { computed, watch } from 'vue';
import { useStore } from 'vuex';
const store = useStore();
const rolledNumbers = computed(() => {
store.getters['rolling/getNumbers'];
});
watch(rolledNumbers, (newValue, oldValue) => {
console.log('Old Array: ' + oldValue);
console.log('New Array: ' + newValue);
});
</script>

我读过一些关于深度观察者的文章,以观察数组值的变化,但我找不到任何适合组合api和的东西。

编辑1:我的观察程序现在在嵌套元素发生更改时启动。这是它的代码:

watch(
rolledNumbers,
(newValue, oldValue) => {
console.log('Old Array: ' + oldValue);
console.log('New Array: ' + newValue);
},
{ deep: true }
);

不幸的是,oldValue和newValue都返回未定义的值。

您的突变正在用一个全新的数组替换numbers中的数组。这意味着对阵列的引用丢失,破坏了反应性:

rollDice(state, payload) {
state.numbers = payload;
}

您需要替换数组的内容,以便保留引用。你可以做一些类似的事情:

rollDice(state, payload) {
# Remove all items from the array
state.numbers.length = 0
# Fill the array with the items from the payload array
[].push.apply(state.numbers, payload)
}

最新更新