I am looking to implement a straightforward Snackbar using VUE 3. While I had no trouble doing this in Vue 2, Vue 3 seems to have some nuances.
Currently, I have stored the messages array in the Vuex store as shown below:
import { createStore } from 'vuex'
export default createStore({
state: {
snackbarText: []
},
mutations: {
DELETE_SNACKBAR_MESSAGE(state) {
state.snackbarBarText.shift()
},
ADD_SNACKBAR_MESSAGE(state, message) {
state.snackbarBarText.push(message)
}
},
getters: {
MESSAGES: (state) => state.snackbarText
}
})
This is what my Snackbar.vue component looks like at the moment:
import { useStore } from 'vuex';
import { ref, watch} from 'vue';
export default {
set() {
const store = useStore();
const text = ref(store.getters["MESSAGES"]);
if (text.value.length) {
let timer = setInterval(() => {
store.commit('DELETE_SNACKBAR_MESSAGE');
if (text.value.length) {
clearInterval(timer)
}
}, 3000)
}
return { text }
}
}
I am trying to figure out how to check the length of the text ref in the Snackbar and trigger a timer function. My challenge lies in implementing this logic in Vue 3's Composition API, which I'm still getting acquainted with.
The expected behavior is for messages to be added to the array and displayed to the user. After 3 seconds, they should be removed from the array. I find using watch cumbersome and struggle with restarting setInterval after it has been stopped.
Any guidance on this issue would be highly appreciated!