V – IF conditional rendering case

Let’s take a simple example: when a user logs in again, he can switch between using a user account or an email address. Similar to the following scenario:

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="app">
  <div></div>
  <span v-if="isShow">{{user_style}}
    <label for="name"></label>
    <input type="text" name="" id="name" :placeholder="user_style">
  </span>
  <span v-else>{{passwd_style}}
    <label for="name1"></label>
    <input type="text" name="" id="name1" :placeholder="passwd_style">
  </span>

  <button @click="changename">Switch type</button>
</div>

<script src=".. /vue.js"></script>

<script>
  const app = new Vue({
    el:"#app".data: {isShow:true.user_style:"User Account".passwd_style:"Password login",},methods: {changename(){
        this.isShow = !this.isShow; }}})</script>
</body>
</html>
Copy the code

There is a small problem: after we input the value, the value in the input box will not disappear when we click the switch button

  • Small problem:
    • If we switch the type with input, we see that the text still shows the previous input.
    • But logically, we should switch to another input element.
    • In the other input element, we have no input.
    • Why is this a problem?
  • Answer to questions:
    • This is because when Vue renders DOM, it tries to reuse existing elements as much as possible for performance reasons, rather than recreating new ones.
      • That is, our two spans and input share the same system, and when rendering to the real scene, they are directly reused, and compared in the reused elements. Different parts are separated and replaced, namely the parts of variables, but the same parts are not moved, and the input is not switched
    • In the above case, the original input element is no longer used inside the Vue and is used directly as input in the else.
  • Solution:
    • If we don’t want the Vue to have similar reuse problems, we can add a key to the corresponding input
    • And we need to make sure that the keys are different

Solution code

<! DOCTYPEhtml>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="app">
  <div></div>
  <span v-if="isShow">{{user_style}}
    <label for="name"></label>
    <input type="text" name="" id="name" :placeholder="user_style" key="abc">
  </span>
  <span v-else>{{passwd_style}}
  <label for="name1"></label>
    <input type="text" name="" id="name1" :placeholder="passwd_style" key="def">
  </span>

  <button @click="changename">Switch type</button>
</div>

<script src=".. /vue.js"></script>

<script>
  const app = new Vue({
    el:"#app".data: {isShow:true.user_style:"User Account".passwd_style:"Password login",},methods: {changename(){
        this.isShow = !this.isShow; }}})</script>
</body>
</html>
Copy the code

Results show