v-else-if

v-else-if 指令

类型: any
限制: 前一兄弟元素必须有 v-if 或 v-else-if。
用法: 表示 v-if 的 “else if 块”。可以链式调用。

代码示例

        <ul id="list">
            <li v-if="type === "A"">A</li>
            <li v-else-if="type === "B"">B</li>
            <li v-else-if="type === "C"">C</li>
            <li v-else>Not A/B/C</li>
        </ul>
		<script type="text/javascript">
			var app=new Vue({
				el:"#list",
				data:{
					type:"B"
				}
			});
		</script>

预览:https://ityanxi.github.io/Vue-tutorial/chapter04/06v-else-if1.html

用 key 管理可复用的元素

Vue 会尽可能高效地渲染元素,通常会复用已有元素而不是从头开始渲染。
这么做,除了使 Vue 变得非常快之外,还有一些有用的好处。
例如,如果你允许用户在不同的登录方式之间切换:

		<div id="no-key-example" class="demo">
			<template v-if="loginType === "username"">
			  <label>Username</label>
			  <input placeholder="Enter your username">
			</template>
			<template v-else>
			  <label>Email</label>
			  <input placeholder="Enter your email address">
			</template>
			<button v-on:click="toggleLoginType()">Toggle login type</button>
		</div>
		<script type="text/javascript">
			new Vue({
			  el: "#no-key-example",
			  data: {
			    loginType: "username"
			  },
			  methods: {
			    toggleLoginType: function () {
			      return this.loginType = this.loginType === "username" ? "email" : "username"
			    }
			  }
			})
		</script>

那么在上面的代码中切换 loginType 将不会清除用户已经输入的内容。因为两个模版使用了相同的元素,<input>不会被替换掉——仅仅是替换了它的的 placeholder。

预览:https://ityanxi.github.io/Vue-tutorial/chapter04/06v-else-if2.html

这样也不总是符合实际需求,所以 Vue 为你提供了一种方式来声明“这两个元素是完全独立的——不要复用它们”。只需添加一个具有唯一值的 key 属性即可:

		<div id="no-key-example" class="demo">
			<template v-if="loginType === "username"">
			  <label>Username</label>
			  <input placeholder="Enter your username" key="username-input">
			</template>
			<template v-else>
			  <label>Email</label>
			  <input placeholder="Enter your email address" key="email-input">
			</template>
			<button v-on:click="toggleLoginType()">Toggle login type</button>
		</div>
		<script type="text/javascript">
			new Vue({
			  el: "#no-key-example",
			  data: {
			    loginType: "username"
			  },
			  methods: {
			    toggleLoginType: function () {
			      return this.loginType = this.loginType === "username" ? "email" : "username"
			    }
			  }
			})
		</script>

预览:https://ityanxi.github.io/Vue-tutorial/chapter04/06v-else-if3.html

文章导航