“for-loop”中的第一个参数下划线(_)代表什么意思?

huangapple go评论56阅读模式
英文:

what does _ mean as first parameter in for-loop

问题

根据此链接,当我浏览和检查下面发布的代码时,吸引了我的注意力

v-for="(_, tab) in tabs"

在下面的代码中显示。

我想知道在 for-loop 中的第一个参数 _ 是什么意思,请。

代码

<script setup>
  import Home from './Home.vue'
  import Posts from './Posts.vue'
  import Archive from './Archive.vue'
  import { ref } from 'vue'
 
  const currentTab = ref('Posts')

  const tabs = {
    Home,
    Posts,
    Archive
  }
</script>

<template>
  <div class="demo">
    <button
       v-for="(_, tab) in tabs"
       :key="tab"
       :class="['tab-button', { active: currentTab === tab }]"
       @click="currentTab = tab"
     >
      {{ tab }}
    </button>
      <component :is="tabs[currentTab]" class="tab"></component>
  </div>
</template>
英文:

referring to this link, and as i peruse and inspect the code posted below,attracted my attention the

v-for=&quot;(_, tab) in tabs&quot;

as shown in the code below.

i would like to know what does _ mean as first parameter in a for-loop please

code:

&lt;script setup&gt;
import Home from &#39;./Home.vue&#39;
import Posts from &#39;./Posts.vue&#39;
import Archive from &#39;./Archive.vue&#39;
import { ref } from &#39;vue&#39;
 
const currentTab = ref(&#39;Posts&#39;)

const tabs = {
  Home,
  Posts,
  Archive
}
&lt;/script&gt;

&lt;template&gt;
  &lt;div class=&quot;demo&quot;&gt;
	&lt;button
	   v-for=&quot;(_, tab) in tabs&quot;
	   :key=&quot;tab&quot;
	   :class=&quot;[&#39;tab-button&#39;, { active: currentTab === tab }]&quot;
	   @click=&quot;currentTab = tab&quot;
	 &gt;
	  {{ tab }}
	&lt;/button&gt;
	  &lt;component :is=&quot;tabs[currentTab]&quot; class=&quot;tab&quot;&gt;&lt;/component&gt;
  &lt;/div&gt;
&lt;/template&gt;

答案1

得分: 2

这只是一个未使用的变量的约定

您真正使用的是Vue的v-for与对象一起使用

v-for=&quot;(value, key) in collection&quot;

但在您的实现中:

  • collection -> tabs
  • value -> _
  • key -> tab

如果这有助于您更好地理解它,考虑一下这个

&lt;button
  v-for=&quot;tabName in Object.keys(tabs)&quot;
  :key=&quot;tabName&quot;
  :class=&quot;[&#39;tab-button&#39;, { active: currentTab === tabName }]&quot;
  @click=&quot;currentTab = tabName&quot;
&gt;
  {{ tabName }}
&lt;/button&gt;
英文:

It's just convention for an unused variable.

What you're really using is Vue's v-for with an Object

v-for=&quot;(value, key) in collection&quot;

But in your implementation:

  • collection -> tabs
  • value -> _
  • key -> tab

If it helps you understand it better, consider this

&lt;button
  v-for=&quot;tabName in Object.keys(tabs)&quot;
  :key=&quot;tabName&quot;
  :class=&quot;[&#39;tab-button&#39;, { active: currentTab === tabName }]&quot;
  @click=&quot;currentTab = tabName&quot;
&gt;
  {{ tabName }}
&lt;/button&gt;

huangapple
  • 本文由 发表于 2023年6月16日 13:05:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76487089.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定