【问题标题】:How to call a method only once in v-for iteration in Vue?如何在Vue的v-for迭代中只调用一次方法?
【发布时间】:2021-07-13 04:39:50
【问题描述】:

我有一种情况,“v-for”为每次迭代调用 2 个方法。当用户按下按钮时调用它们。

用户告诉组件 v-for 将运行的迭代次数(itemsDrawn 属性)。

"itemsDrawn" 属性可以在 0 到 4 之间变化。 v-for 在每次迭代中抽取引导卡(可以是 0 到 4)

这些方法(方法 A 和 B)返回一个整数/代码或字符串(我可以决定),并且在模板内我需要根据为每个函数提供的代码(数据类型)显示一些消息。

因此,根据这些代码,我可以选择要在 UI 中显示的文本。

截取的代码是这样的:

<div
  class="card text-center mt-5"
  style="width: 18rem"
  v-for="(item, index) in itemsDrawn"
  :key="index"
>
  <div class="card-header">Item: {{ item }} - {{ methodA() }}</div>
  <div class="card-body">
    <h5 class="card-title">{{ methodB() }}</h5>
    <p class="card-text">
      'This is the message based on both methodA() and methodB()'
      'I NEED TO CALL A METHOD HERE 
    </p>
  </div>
</div>

方法

  methods: {
    methodA(){
      return this.workItemsTypes[this.randomNumber(0,9)];
    },
    methodB() {
      return this.classesOfServices[this.randomNumber(0,7)];
    },
  },

输出是这样的:

查看输出的第一列,卡片标题中的“Melhoria”和卡片正文中的“Padrão”应该显示个性化消息;每张卡都会发生同样的情况。

如果我在 p-card-text 中调用这些方法,它们会给我其他值。因此,这将是 4 次调用,每个方法 2 次。

那么,我怎样才能只调用它们一次,保留它们的输出并根据它们的数据显示一条消息?

如何在每个调用的方法中保留这两个值并在以后使用它们?

【问题讨论】:

  • Vue 的快速经验法则...不要使用方法来渲染模板的某些部分。请改用计算属性。见Method vs Computed in Vue
  • “基于用户操作”是什么意思。您的伪代码模板示例没有传达您要执行的操作。你认为你可以改进它以使其更清晰吗?
  • 将随机值存储在data状态,不要在渲染中使用随机性。

标签: javascript vue.js


【解决方案1】:

我不确定这是否是最好的设计,但根据 cmets 我可以找到答案。

classOfServiceItemworkItemTypeItem 都是状态变量,我在通过对应的数据数组检索之前保存数据。

保存状态中的随机数

  state: {
    classOfServiceItem: 0,
    workItemTypeItem: 0,
  },
  methods: {
    classOfService() {
      // here I save the state
      this.classOfServiceItem = this.randomNumber(0, 7);
      return this.classesOfServices[this.classOfServiceItem];
    },
    workItemType() {
      // here I save the state
      this.workItemTypeItem  = this.randomNumber(0, 0);
      return this.workItemsTypes[this.workItemTypeItem];
    },


  },

使用每次迭代的状态

 
        <div class="card-body mycard-body">
          <h5 class="card-title">{{ classOfService() }}</h5>
          <p class="card-text">
            'Here I use the random    
            'This is the message based on both 
{{ classesOfServices[classOfServiceItem]  }} and 
{{ workItemsTypes[workItemTypeItem] }}'
          </p>
          <button type="button" @click="pullItem" class="btn btn-primary">
            Puxar
          </button>
        </div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多