I’am trying to access a store value after i have mutated it in a component.
First, i select an array of numbers from a list, which then after a button is pressed gets stored in in the store. When i try to Access the Value from the store it is still empty.
My Vue Component:
<template>
<MultiSelect
class="groupselect"
v-model="localSelectedNumbers"
:options="options"
optionLabel="id"
placeholder="Wähle Geräte"
/>
<v-btn @click="refresh()">Click</v-btn>
<p>{{selectedNumbers}}</p>
</template>
<script>
import MultiSelect from "primevue/multiselect";
import {mapMutations, mapState} from "vuex";
export default {
name: "Gerateauswahl",
components: {MultiSelect},
computed: {
...mapState([
'mode',
'selectedNumbers',
'options'
])
},
data() {
return {
localSelectedNumbers: [],
show: []
}
},
watch: {
selectedNumbers(newValue, oldValue) {
this.show = newValue
}
},
methods: {
...mapMutations([
'setRows'
]),
refresh() {
this.setRows(JSON.parse(JSON.stringify(this.localSelectedNumbers)))
//console.log(this.selectedNumbers)
}
}
}
</script>
My Store:
import {createStore} from "vuex";
const store = createStore({
state() {
return {
options : [
{id:1}, {id:2}, {id:3}
],
rows: [],
mode: false,
selectedNumbers: []
}
},
mutations: {
setRows(state, payload) {
console.log(state.rows)
state.rows = payload
console.log(state.rows)
},
}
export default store;
I’ve tried with watchers, manuel refresh.
The console.log output in the Store: (trying with numbers 1 and 2)
<target>: Array [ {…}, {…} ]
0: Object { id: 1 }
1: Object { id: 2 }
length: 2
<prototype>: Array []
<handler>: Object { get: get(target, key, receiver), set: set(target, key, value, receiver), deleteProperty: deleteProperty(target, key), … }
but the selectedNumbers Variable in the Vue Component stays empty, as well as the this.$store.state.selectedNumbers when accessed from the Component.
2
Answers
It is because you are updating
rows
in mutation but you are watchingselectedNumbers
. I think your mutation should look something like thisYou’re updating
rows
state in the mutation but you callingselectedNumbers
in the component..You need to update
selectedNumbers
instead in the mutation or callrows
state in the component