Vue.js 中的条件渲染是根据数据的不同状态有选择性地显示或隐藏页面元素的技术。在这篇博客中,我们将通过一个简单的示例来介绍 v-if
、v-else-if
、v-else
和 v-show
这几个关键指令的用法。
示例代码解析
<template><div><h1 v-if="isAwesome">Vue 很棒!</h1><h1 v-else-if="isGood">Vue 不错!</h1><h1 v-else>哦,不,Vue 既不棒也不错 😢</h1><button @click="toggleAwesome">切换 'isAwesome'</button><button @click="toggleGood">切换 'isGood'</button><h2 v-show="isVisible">这个元素一直显示,使用了 v-show</h2><template v-if="showTemplate"><h3>这是位于 template 内的标题</h3><p>它是有条件渲染的!</p></template></div>
</template><script>
export default {data() {return {isAwesome: true,isGood: false,isVisible: true,showTemplate: true};},methods: {toggleAwesome() {this.isAwesome = !this.isAwesome;},toggleGood() {this.isGood = !this.isGood;}}
};
</script><style>
</style>
主要
- 使用
v-if
、v-else-if
和v-else
根据数据状态渲染不同的标题。 - 通过按钮点击切换数据状态,演示了动态改变内容的实现。
- 使用
v-show
控制元素的显示与隐藏,与v-if
的区别在于元素始终存在于DOM中。 - 利用
<template>
元素上的v-if
包含多个元素,最终渲染时不保留<template>
元素本身。