【问题标题】:Set data field from getter and add extra computed field从 getter 设置数据字段并添加额外的计算字段
【发布时间】:2020-01-27 17:33:42
【问题描述】:

我想使用 getter 在数据中设置字段:

export default {
 data () {
    return {
        medications: [],
       }
   },
  computed: {
  ...mapGetters([
        'allMedications',
        'getResidentsById',
    ]),

我想设置medications = allMedications,我知道我们可以使用{{allMedications}},但我的问题是假设我有:

medications {
    name: '',
    resident: '', this contains id
    .......
   }

现在我想致电 getResidentsById 并在 medications 上设置一个额外字段:

  medications {
    name: '',
    resident: '', this contains id
    residentName:'' add an extra computed field
    .......
   }

我是这样做的:

watch: {
  allMedications() {
      // this.medications = this.allMedications
      const medicationArray = this.allMedications
      this.medications = medicationArray.map(medication => 
    ({
        ...medication,
        residentName: this.getResidentName(medication.resident)
    })
    );
    },
 },
 method: {
    getResidentName(id) {
      const resident = this.getResidentsById(id)
      return resident && resident.fullName
    },
  }

但这似乎有问题,因为只有当 allMedications 发生变化时,watch 上的方法才会激活并设置 residentName。 p>

【问题讨论】:

    标签: vue.js vuejs2 vue-component vuex


    【解决方案1】:

    在这种情况下,您会希望在创建组件后立即运行观察程序。您可以在方法中移动逻辑,然后从观察者和创建的钩子中调用它,但有一种更简单的方法。

    您可以使用观察者的long-hand version 来传递immediate: true 选项。这将使它在计算属性被解析后立即运行。

    watch: {
      allMedications: {
        handler: function (val) {
          this.medications = val.map(medication => ({
            ...medication,
            residentName: this.getResidentName(medication.resident)
          });
        },
        immediate: true
      }
    }
    

    【讨论】:

    • 手表中的 allMedication 在加载页面上也被调用了两次。是否因为第一次在创建期间调用它,然后设置 getter 中的 allMedication 并再次调用手表?
    猜你喜欢
    • 2013-05-04
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 2015-08-26
    相关资源
    最近更新 更多