Vue.js笔记3—条件渲染

134 阅读1分钟

v-if

  • 指令表达式返回 true时才会渲染内容

    <div id="app">
        <h1 v-if="cool">cool~~~</h1>
    </div>
    
    data: {
        cool: true
    },
    
  • 可以与v-else配合,如果不是true将返回v-else的内容

    <div id="app">
        <h1 v-if="cool">cool~~~</h1>
        <h1 v-else>what?</h1>
    </div>
    
  • 多个条件时可以用v-else-if

    <div id="app">
        <h1 v-if="cool===1">cool~~~~</h1>
        <h1 v-else-if="cool===2">what?</h1>
        <h1 v-else="cool===3">I don't know </h1>
    </div>
    
    data: {
        cool: 2
    },
    

key

  • 一般情况下,Vue会复用已有元素

    <div id="app">
        <template v-if="username">
            Username:<input placeholder="Enter your username">
        </template>
    
        <template v-else>
            Email:<input placeholder="Enter your email address">
        </template>
    
        <br/><input type="button" @click="username=!username" value="change">
    </div>
    
    data: {
        username: true
    },
    

    template可用于包裹元素。在上面例子中,如果你已经输入了内容,由于Vue的复用,切换时内容将不会清空

  • key管理可复用元素,将元素独立开。应用时只需在需要独立的元素上加上不同的key值

    Username:<input placeholder="Enter your username" key="1">
    Email:<input placeholder="Enter your email address" key="2">
    

v-show

  • v-show 的元素始终会被渲染并保留在 DOM 中。v-show 只是简单地切换元素的 CSS property display

    <h1 v-show="show">Hello!</h1>
    
  • 不支持<template>