• Home
  • Recent Q&A
  • Java
  • Cloud
  • JavaScript
  • Python
  • SQL
  • PHP
  • HTML
  • C++
  • Data Science
  • DBMS
  • Devops
  • Hadoop
  • Machine Learning
in Vue.JS by
Q:

How do you reuse elements with key attribute?

1 Answer

0 votes
by

Vue always tries to render elements as efficient as possible. So it tries to reuse the elements instead of building them from scratch. But this behavior may cause problems in few scenarios. For example, if you try to render the same input element in both v-if and v-else blocks then it holds the previous value as below,

<template v-if="loginType === 'Admin'">
  <label>Admin</label>
  <input placeholder="Enter your ID">
</template>
<template v-else>
  <label>Guest</label>
  <input placeholder="Enter your name">
</template>

In this case, it shouldn't reuse. We can make both input elements as separate by applying key attribute as below,

    <template v-if="loginType === 'Admin'">
      <label>Admin</label>
      <input placeholder="Enter your ID" key="admin-id">
    </template>
    <template v-else>
      <label>Guest</label>
      <input placeholder="Enter your name" key="user-name">
    </template>

Related questions

0 votes
asked Oct 9, 2019 in Vue.JS by Indian
0 votes
asked Oct 21, 2019 in Vue.JS by Tate
...