Vuex商店-变量仅在商店中更新,而不是全局更新

myss37ts  于 2023-05-01  发布在  Vue.js
关注(0)|答案(2)|浏览(172)

已解决:我没有注意到我使用了错误的变量

我试图访问一个存储值后,我已经变异了它在一个组件。首先,我从一个列表中选择一个数字数组,然后按下按钮后,这个数组将存储在存储器中。当我尝试从存储访问值时,它仍然是空的。
我的Vue组件:

<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>

我的店铺:

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;

我试过观察者,曼纽尔刷新。控制台存储中的日志输出:(尝试数字1和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), … }

但是Vue组件中的selectedNumbers变量和this变量保持为空。$store.state.selectedNumbers。

zkure5ic

zkure5ic1#

您正在更新变化中的rows状态,但您在组件中调用了selectedNumbers。.您需要在组件中的mutationcall rows状态中更新selectedNumbers

anauzrmj

anauzrmj2#

这是因为你在mutation中更新了rows,但你正在监视selectedNumbers。我认为你的突变应该是这样的

mutations: {
  setRows(state, payload) {
    console.log(state.selectedNumbers);
    state.selectedNumbers = payload.map(item => item.id);
    console.log(state.selectedNumbers);
  },
}

相关问题