head-img Force's Blog

Vue组件之间(兄弟、父子)监听vuex state变化

JavaScript

情景

两个组件,A和B。 B组件想通过vuex控制A组件方法实现刷新。

准备

1.进入store设置state:reloadLic: false

export default {
  ...
  reloadLic: false,
}

2.进入store设置mutationschangeReloadLic()

export default {
  changeReloadLic(state, data) {
    state.reloadLic = data;
  },
}

3.进入组件A设置监听this.$store.state.reloadLic,注意其中computed中reloadLic不能在data(return{})中定义!

export default {

  methods: {
    loadLic() {
        //...刷新逻辑
    },
  }

  computed: {
    reloadLic() {
      return this.$store.state.reloadLic;
    },
  },

  watch: {
    reloadLic: {
      handler(status) {
        if(status) {
          this.loadLic();
          this.$store.commit("changeReloadLic", false);
        }
      },
      deep: true,
      immediate: true,
    },
  },
}

4.进入组件B根据情况条件触发修改state

export default {
  mounted() {
     this.$store.commit("changeReloadLic", true); 
  }
}

触发后B组件监听可实现通过this.$store.state.reloadLic == true刷新A组件loadLic()方法

点我评论
打赏本文
二维码


125

文章

14

标签

 访客统计  Update-******