Vue.js条件渲染如何理解,请看代码示例

2019-03-2923:02:42WEB前端开发Comments2,344 views字数 1009阅读模式

Vue.js条件渲染如何理解,请看代码示例文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

什么是条件渲染?文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

条件渲染意味着,如果某个特定条件为真,则从dom中添加或删除元素。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

Vue中,我们需要使用v-if指令来有条件地渲染元素。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

让我们看一个例子:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

<template>
  <div>
  <!-- v-if="javascript expression" -->
   <h1 v-if="isActive">Hello Vuejs</h1>
   <button @click="isActive= !isActive">点击</button>
  </div>
</template>

<script>

export default{
    data:function(){
        return{
            isActive:false
        }
    }
}
</script>

在上面的代码中,我们添加了一个带有属性isActivev-if指令,因此如果isActive属性为trueh1元素只渲染到dom中。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

我们还可以在v-if指令之后扩展v-else指令。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

 <h1 v-if="isActive">Hello Vuejs</h1>
   <h1 v-else>Hey Vuejs</h1>

如果isActive属性为真,则第一个h1元素将渲染,否则第二个h1元素将渲染到dom中。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

我们还可以使用v-else-if块进一步扩展它。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

<h1 v-if="isActive">Hello Vuejs</h1>
   <h1 v-else-if="isActive && ">You're vuejs</h1>
   <h1 v-else>Hey Vuejs</h1>

JavaScript中,v-else-if指令的工作原理类似于else-if块。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

注意:一个v-else元素必须紧跟一个v-if元素或v-if-else元素,否则将无法识别它。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

如何有条件地渲染多个元素?文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

有时我们必须有条件地渲染多个元素,在这种情况下,我们需要将元素组合在一起。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

<template>
  <div v-if="available">
    <h1>Items are available</h1>
    <p>More items in the stock</p>
  </div>
  <div v-else>
    <h1>Items are not available</h1>
    <p>Out of stock</p>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      available: true
    };
  }
};
</script>

在这里,我们将div标签中的多个元素分组。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

Vue.js条件渲染如何理解,请看代码示例文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/10663.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/10663.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定