【问题标题】:make something after vuex state change在 vuex 状态改变后做点什么
【发布时间】:2021-09-07 14:20:39
【问题描述】:

??????‍??????????‍???? 我有这些问题,我已经阅读了很多关于这些问题的内容,但我不明白为什么它不起作用。我有两个组件,一个将数据发送到 vuex 中的数组,但是当这些数据发生变化时我想触发一些东西。

这些是我作为复选框输入的简单值列表的组成部分:

<div
        v-for="item in items"
        v-bind:key="item.label"
        class="text-white flex align-items-center mr-3 mb-2 md:mb-0"
      >
        <input
          @click="getSelectedLocations()"
          v-model="item.value"
          type="checkbox"
          name="option"
          class="
            h-7
            w-7
            bg-white
            text-indigo-600
            focus:ring-indigo-500
            rounded-sm
            m-1
            border-white
          "
        />
        <p class="mt-1 text-xl">{{ item.label }}</p>
      </div>

///theMethod

methods: {
    getSelectedLocations() {
      this.$store.commit("selectedLocationsByUser", this.items);
    },
  },


我的数据发送到其他组件对吗????,但我需要知道状态何时发生变化:

computed: {
    ...mapState(["selectedLocations"]),
    ...mapGetters(["userProfile"]),
  },
  watch: {
    selectedLocations(nv, ov) {
      console.log(nv);
      console.log("old:", ov);
    },
  },

我的 Vuex

export default createStore({
  state: {
    selectedLocations: [],
  },
  mutations: {
    selectedLocationsByUser(state, payload) {
      state.selectedLocations = payload;
    },
  },
  actions: {},
  modules: {},
  getters: {},

控制台向我显示了 1 个更改,但是当我再次选择复选框组件上的值时,它不会触发监视功能。知道有什么问题吗? ??????????‍????

【问题讨论】:

  • 你能分享你处理这个突变的 Vuex sn-p 吗?
  • 舒尔,@anatolhiman,谢谢。

标签: vue.js vuex


【解决方案1】:

由于状态是一个数组,您需要将deep:true 选项添加到观察者,并将输入直接绑定到状态:

computed: {
  
    ...mapGetters(["userProfile"]),

   selectedLocations:{
        get(){ return this.$store.stateselectedLocations},
        set(val){
           this.$store.commit("selectedLocationsByUser", val);
        } 

   }
  },
  watch: {
  selectedLocations:{
     handler(nv, ov) {
       console.log(nv);
       console.log("old:", ov);
     },
     deep:true
    }
  },

在模板中:

<input    v-model="selectedLocations" :value="item.value"
          type="checkbox"
          name="option"
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 2017-08-01
    • 2018-04-16
    • 2020-03-08
    • 1970-01-01
    • 2021-03-05
    相关资源
    最近更新 更多