Vue v-else-if 指令
实例
如果条件为 'true',则使用 v-else-if 指令创建 <div> 元素。
<div v-if="word === 'apple'"><img src="/img_apple.svg" alt="apple" /><p>The value of the 'word' property is 'apple'.</p></div><div v-else-if="word === 'pizza'"><img src="/img_pizza.svg" alt="pizza" /><p>The value of the 'word' property is 'pizza'</p></div>
定义与用法
v-else-if 指令用于有条件地呈现元素。v-else-if 指令只能在带有 v-if 的元素之后使用,或在带有 v-else-if 的另一个元素之后使用。在元素上使用 v-else-if 时,它后面必须跟一个表达式:
- 如果表达式的计算结果为 'true',则在 DOM 中创建元素及其所有内容。
- 如果表达式的计算结果为 'false',则元素将被销毁。
使用 v-else-if 切换元素时:
- 当元素进入和离开 DOM 时,我们可以使用内置的 <Transition> 组件来设置动画。
- 会触发生命周期钩子,如 'mounted' 和 'unmounted'。
条件呈现指令
此概述描述了用于条件呈现的不同 Vue 指令是如何一起使用的。
| 指令 | 详情 |
|---|---|
| v-if | 可以单独使用,也可以与 v-else-if ,或 v-else 一起使用。如果 v-If 内部的条件为 true,则不考虑 v-else-If 或 v-else。 |
| v-else-if | 必须在 v-if 或另一个 v-else-if 之后使用。如果 v-else-If 内部的条件为 true,则不考虑后面的 v-else-If 或 v-else。 |
| v-else | 如果 if 语句的第一部分为 false,则会发生此部分必须放在 if 语句的最后,在 v-if 和 v-else-if 之后。 |
更多实例
实例 1
使用 v-else-if 写上 "Very few left!"(所剩无几!)以防库存中只剩下1、2或3台打字机。
<p v-if="typewriterCount>3">In stock</p><p v-else-if="typewriterCount>0">Very few left!</p><p v-else>Not in stock</p>
实例 2
如果句子中包含 'burrito',则使用 v-else-if 来显示特定的文本和图像。
<div id="app"><div v-if="text.includes('pizza')"><p>The text includes the word 'pizza'</p><img src="img_pizza.svg"></div><div v-else-if="text.includes('burrito')"><p>The text includes the word 'burrito', but not 'pizza'</p><img src="img_burrito.svg"></div><p v-else>The words 'pizza' or 'burrito' are not found in the text</p></div><script src="https://unpkg.com/vue@3/dist/vue.global.js"></script><script>const app = Vue.createApp({data() {return {text: 'I like taco, pizza, Thai beef salad, pho soup and tagine.'}}})app.mount('#app')</script>
实例 3
使用 v-else-if 链来翻转图像,使用 <Transition> 组件来创建动画。
App.vue:
<template><h1>mode="out-in"</h1><p>Click the button to get a new image.</p><p>With mode="out-in", the next image is not added until the current image is removed. Another difference from the previous example, is that here we use computed prop instead of a method.</p><button @click="indexNbr++">Next image</button><br><Transition mode="out-in"><img src="/img_pizza.svg" v-if="imgActive === 'pizza'"><img src="/img_apple.svg" v-else-if="imgActive === 'apple'"><img src="/img_cake.svg" v-else-if="imgActive === 'cake'"><img src="/img_fish.svg" v-else-if="imgActive === 'fish'"><img src="/img_rice.svg" v-else-if="imgActive === 'rice'"></Transition></template><script>export default {data() {return {imgs: ['pizza', 'apple', 'cake', 'fish', 'rice'],indexNbr: 0}},computed: {imgActive() {if(this.indexNbr >= this.imgs.length) {this.indexNbr = 0;}return this.imgs[this.indexNbr];}}}</script><style scoped>.v-enter-active {animation: swirlAdded 0.7s;}.v-leave-active {animation: swirlAdded 0.7s reverse;}@keyframes swirlAdded {from {opacity: 0;rotate: 0;scale: 0.1;}to {opacity: 1;rotate: 360deg;scale: 1;}}img {width: 100px;margin: 20px;}img:hover {cursor: pointer;}</style>