v-if/v-else/v-elseif的使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <div v-if="isShow"> <h3>asd</h3> <h3>asd</h3> <h3>asd</h3> <h3>asd</h3> <h3>{{message}}</h3> </div> <div v-else> 否则就显示我 </div> <h3 v-if="score >= 90">优秀</h3> <h3 v-else-if="score >= 80">良好</h3> <h3 v-else-if="score >= 60">及格</h3> <h3 v-else>不及格</h3> <h3>{{result}}</h3> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: '你好啊', isShow: true, score: 99 }, computed: { result() { let showMessage = ''; if(this.score >= 90) { showMessage = '优秀' }else if(this.score >= 80) { showMessage = '良好' }else if(this.score >= 60) { showMessage = '及格' }else { showMessage = '不及格' } return showMessage } } }) </script> </body> </html>
小案例(用户切换登录方式)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <span v-if="isShow"> <label for="username">用户账号 </label> <input type="text" id="username" placeholder="用户账号" key="username"> </span> <span v-else> <label for="email">用户邮箱 </label> <input type="text" id="email" placeholder="用户邮箱" key="email"> </span> <!--虚拟DOM: Vue不会把DOM直接让浏览器渲染(有些不必要的元素可以不进行渲染),它会先放在缓存中,根据需要再进行渲染--> <button @click="isShow = !isShow">切换方式</button> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: '你好啊', isShow: true } }) </script> </body> </html>
v-if/v-show的区别
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="app"> <!--v-if相当于是删除元素了--> <h3 v-if="isShow" id="aaa">{{message}}</h3> <!--<h3 id="bbb" style="display: none;">你好啊</h3>--> <h3 v-show="isShow" id="bbb">{{message}}</h3> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { message: '你好啊', isShow: true } }) </script> </body> </html>