Vue.js 组件更新一个存储状态变量,但不更新另一个

问题描述 投票:0回答:2

我正在使用 Vuex 和 Composition API 编写一个 Vue 3 应用程序。

我也遇到过这样的问题。

组件根据两个存储状态变量的状态显示元素。第一个是数组,第二个是布尔值。一个已正确更新,第二个未正确更新。

店铺代码:

export default {
    state() {
        return {
            current: {
                chat: {
                    them_writing: false,
                    texts: []
                }
            }
        }
    },
    mutations: {
        add_text_to_chat(state, text) {
            state.current.chat.texts.push(text);
        },
        set_them_writing(state, v) {
            state.current.chat.them_writing = v;
        }
    }
};

组件代码:

<template>
  <div v-if="them_writing || shown.length">

    <div class="text_wrapper" v-for="(text, index) in shown" :key="index">
      <div class="text">
        {{ text.content }}
      </div>
    </div>

    <div class="text" v-if="them_writing">
      <span>.</span>
      <span>.</span>
      <span>.</span>
    </div>
  </div>
</template>

<script setup>
import {  inject, ref } from "vue";

let store = inject("$store");

const shown = ref(store.state.network.current.chat.texts);
const them_writing = ref(store.state.network.current.chat.them_writing);
</script>

<style scoped>
</style>

每当我使用

add_text_to_chat
突变添加文本时,元素列表都会正确更新。

但是,当我使用新值调用

set_them_writing
时,UI 不会反映更改。

由于第一个状态变量是反应性的,我知道这不是商店设置。

设置相同,但不遵循一个值。谁能解释一下为什么吗?

javascript vue.js vuex vue-composition-api
2个回答
0
投票

首先,我认为你应该直接将 current.chat 声明为响应式,而不是 current.chat.them_writing 。然后每次更改都更新 current.chat


0
投票

在您的代码中,您使用 Composition API 与 Vue 3 和 Vuex 来管理状态。

您面临的问题是一个状态变量正确更新,而另一个状态变量没有正确更新,可能与反应性有关。

当您使用 ref(store.state.network.current.chat.texts) 和 ref(store.state.network.current.chat.them_writing) 初始化 shown 和 them_writing 时,这些引用在组件设置期间仅创建一次,并且它们当 Vuex 存储中的状态发生变化时,不会自动更新。

这就是为什么显示的内容可能无法正确反映更改。

为了确保您的 shown 和 them_writing 变量是反应性的,并在相应的状态变量发生变化时更新,您应该使用计算属性。

以下是修改脚本设置以实现此目的的方法:

<script setup>


import { inject, computed } from "vue";

let store = inject("$store");

const shown = computed(() => store.state.network.current.chat.texts);
const them_writing = computed(() => store.state.network.current.chat.them_writing);

</script>

通过使用计算属性,shown 和 them_writing 将在底层 Vuex 状态变量发生变化时进行响应式更新,这应该可以解决一个值无法在 UI 中正确反映变化的问题。

© www.soinside.com 2019 - 2024. All rights reserved.