I’m writing a Vue 3 app using Vuex and Composition API.
I’ve run into such a problem.
A component displays elements depending on the state of two store state variables. One is an array and the second is the boolean. One is updated properly and the second one not.
Store code:
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;
}
}
};
Component code:
<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>
Whenever I add text using add_text_to_chat
mutation, the elements list is updated properly.
However when I call set_them_writing
with the new value, the UI doesn’t reflect the change.
As the first state variable is reactive, I know it’s not the store setting.
The setting is the same yet one value is not followed. Can anybody explain why?
2
Answers
First, I think you should declare the current.chat as reactive directly, instead of current.chat.them_writing. And then update the current.chat per change
In your code, you’re using the Composition API with Vue 3 and Vuex to manage state.
The issue you’re facing, where one state variable updates properly while the other doesn’t, could be related to reactivity.
When you initialize shown and them_writing using ref(store.state.network.current.chat.texts) and ref(store.state.network.current.chat.them_writing), these references are created only once during component setup, and they won’t automatically update when the state changes in the Vuex store.
This is why shown may not reflect changes properly.
To ensure that your shown and them_writing variables are reactive and update when the corresponding state variables change, you should use computed properties instead.
Here’s how you can modify your script setup to achieve this:
By using computed properties, shown and them_writing will reactively update whenever the underlying Vuex state variables change, and this should resolve the issue of one value not reflecting changes properly in your UI.