无法将函数返回推入vue3模态

问题描述 投票:0回答:1

我有一个根据可点击按钮过滤数据的功能(在控制台日志中看到)。当我将此数组作为 v-for '循环' 放入模态中时,我破坏了按钮功能。为什么?每次我这样做时,都会得到“未定义”的结果。这个想法对于显示基于 skedDatas 数组的表行数据效果很好。

/src/pages/courses/ammo04.vue 中的函数 getrowid。代码位于github:https://github.com/EnergeticPixels/catalog

modal-dialog vuejs3 v-for
1个回答
0
投票

我不会直接在组件的模板中调用方法。每当发生重新渲染时,该方法都会重新运行,如果您不非常小心,这将导致问题和其他副作用。我建议使用 ref 变量来保存数据。由于作用范围为整个组件,您可以在脚本和模板代码中使用它,而无需在任何地方传递/返回它。

首先,更新按钮以将

classId
作为参数传递给toggleModal函数,表明Vue不需要使用数据属性:

<td><button @click.prevent="toggleModal(skedData.classId)">{{ skedData.contact }}</button></td>
const toggleModal = (classId) => {
  getclickedrow(classId);
  modalActive.value = !modalActive.value;
}

再次将其作为参数传递给

getclickedrow
并使用 ref 来保存数组过滤器的结果(如果预期结果始终是 1 个对象,我将其更改为 Array.find,我认为它是.. .):

const skedfiltered = ref(null);
const getclickedrow = (classId) => {
  skedfiltered.value = skedDatas.find(offering => {
    return offering.classId === classId
  });
};

我看到下一个代码被注释掉了,但我注意到如果将其制作成计算属性,它将根据上面的

skedfiltered
参考自动重新评估自身,总是为您提供所需的 Poc。 Array.find 看起来也比 Array.filter 更好。只是要小心,当
skedfiltered
最初为空时,查找或过滤将不起作用(因此使用 可选链接 来捕获它)

// filter sitePoc array for matching clicked contactId
const filteredPoc = computed(() => sitePocs.find(poc => {
  return poc.contactId === skedfiltered.value?.contactId
}))

计算需要导入,因此更改顶部的行:

import { ref, computed } from 'vue';

最后,设置模板代码的其余部分以显示上面评估的所有数据:

<ContactInfo v-if="filteredPoc" :filteredPoc="filteredPoc" class='contactInfo' @close="toggleModal" :modalActive="modalActive">
  <h2 class="title has-text-centered is-size-3">{{ filteredPoc.pocTitle }}</h2>
  <p class="">Please contact the following individual(s):</p>
  <ul>
    <li><span class="has-text-weight-bold">Name:</span> {{ filteredPoc.pocName }}</li>
    <li><span class="has-text-weight-bold">Email:</span> {{ filteredPoc.pocEmail }}</li>
    <li><span class="has-text-weight-bold">Commercial Phone 1:</span> {{ filteredPoc.pocPhone1 }}</li>
    <li><span class="has-text-weight-bold">Commercial Phone 2:</span> {{ filteredPoc.pocPhone2 }}</li>
    <li><span class="has-text-weight-bold">DSN:</span> {{ filteredPoc.pocdsnPhone }}</li>
  </ul>
  <div v-if="filteredPoc.altpocName">
    <p class="">Or their alternate:</p>
    <ul>
      <li><span class="has-text-weight-bold">Name:</span> {{ filteredPoc.altpocName }}</li>
      <li><span class="has-text-weight-bold">Email:</span> {{ filteredPoc.altpocEmail }}</li>
      <li><span class="has-text-weight-bold">Commercial Phone 1:</span> {{ filteredPoc.altpocPhone1 }}</li>
      <li><span class="has-text-weight-bold">Commercial Phone 2:</span> {{ filteredPoc.altpocPhone2 }}</li>
      <li><span class="has-text-weight-bold">DSN:</span> {{ filteredPoc.altpocdsnPhone }}</li>
    </ul>
  </div>
</ContactInfo>

添加了

v-if="filteredPoc"
,用于防止错误。即使模态不可见,所有元素都会渲染到 DOM,并且如果
filteredPoc
为 null(并且最初为 null),所有尝试使用它的元素都会导致错误,因此
v-if
将阻止这种情况发生。当 modalActive 切换为 true 时,v-if 将计算为 true,因此应该一切正常。

© www.soinside.com 2019 - 2024. All rights reserved.