【问题标题】:How to update vue component data item from vuex store based on condition如何根据条件从 vuex 存储更新 vue 组件数据项
【发布时间】:2020-08-26 09:55:21
【问题描述】:

仅当条件为真时,我才需要使用 vuex 存储 getter 更新“slotParams”属性。在下面的代码中,在第一次为真检查后,vue 开始观察“this.$store.getters.ENCOUNTER.params”并更新“slotParams”,无论条件是真还是假。

props: {
  name: { required: true }
},
data(){
  return {
    slotParams: {}
  }
},
computed: {
  isActive() {
    const encounter = this.$store.getters.ENCOUNTER
    if(encounter.name === this.name){
      this.slotParams = encounter.params
      return true
    }
    return false
  }
},

我想要的示例如下。我需要中断反应并控制手动更新它。

props: {
  name: { required: true }
},
data(){
  return {
    slotParams: {}
  }
},
computed: {
  isActive() {
    const encounter = this.$store.getters.ENCOUNTER
    if(encounter.name === this.name){
      this.slotParams = JSON.parse( JSON.stringify(encounter.params) )
      return true
    }
    return false
  }
},

有没有办法以正确的方式做到这一点?

【问题讨论】:

    标签: javascript vue.js vuex


    【解决方案1】:

    如果存储数据发生变化,并且这是被动完成的,您可以像下面那样使用 mapGetters,也不要直接使用计算值设置值,您在 isActive 中所做的更多是一种方法,使用计算属性通常会导致无休止的变化循环。

    如果我理解正确,我会尝试以下内容。

    import { mapGetters } from 'vuex';
    
    export default {
       props: {
          name: {
             type: String,
             required: true
          }
       },
    
       data() {
          return {
             slotParams: {}
          }
       },
    
       computed: {
          ...mapGetters({
             encounter: 'whatever-your-path-is/encounter'
          });,
    
          isActive() {
             return this.encounter.name === this.name;
          }
       },
    
       watch: {
          encounter: {
             deep: true,
             handler() {
                // This might be where you want to check conditional for this.isActive
                this.slotParams = JSON.parse(JSON.stringify(this.encounter.params));
    
                /*
                   if (this.isActive) {
                      this.slotParams = JSON.parse(JSON.stringify(this.encounter.params));
                   }
                */
             }
          }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-20
      • 2018-06-14
      • 2020-09-05
      • 2019-10-05
      • 2021-12-25
      • 1970-01-01
      • 2018-09-04
      • 2019-11-25
      • 2021-09-02
      相关资源
      最近更新 更多