skip to Main Content

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


  1. It is because you are updating rows in mutation but you are watching selectedNumbers. I think your mutation should look something like this

    mutations: {
      setRows(state, payload) {
        console.log(state.selectedNumbers);
        state.selectedNumbers = payload.map(item => item.id);
        console.log(state.selectedNumbers);
      },
    }
    
    Login or Signup to reply.
  2. You’re updating rows state in the mutation but you calling selectedNumbers in the component..
    You need to update selectedNumbers instead in the mutation or call rows state in the component

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search