Vue的条件渲染是使用v-if , v-else,v-show等指令实现元素的移除,样式隐藏,显示等
案例如下代码:
<div id="demo"> <p v-if="ok">成功了</p> <p v-else>失败了</p> <p v-show="ok">表白成功</p> <p v-show="!ok">表白失败</p> <button @click="ok=!ok">切换</button> </div> <script src="../js/vue.min.js"></script> <script type="text/javascript"> new Vue({ el:'#demo', data:{ ok:false }, })
在点击切换之前如下效果:
点击切换之后效果如下:
<div id="demo"> <h2> 测试:v-for 遍历数组</h2> <ul> <li v-for="(p,index) in persons" :key='index'> {{index}}---{{p.name}}---{{p.age}} ---<button @click="deleteP(index)">删除</button> ---<button @click="updateP(index,{name:'cat',age:56})">更新</button> </li> </ul> <h2> 测试:v-for 遍历对象</h2> <ul> <li v-for=" (value,key) in persons[0]" :key='key'> {{key}}---{{value}} </li> </ul> </div> <script src="../js/vue.min.js"></script> <script type="text/javascript"> //vue本身只是监视了persons的改变,但没有监视数组内部数据的改变 //vue重写了数组中的一系列改变数组内部数据的方法(先是原生的调用,后是更新界面)--数组内部改变,界面更新 new Vue({ el:'#demo', data:{ persons:[ {name:'tom',age:18}, {name:'jack',age:20}, {name:'Bob',age:15}, {name:'rose',age:26}, ] }, methods:{ deleteP:function(index){ //删除persons中指定index的P this.persons.splice(index,1); }, updateP:function(index,newP){ //this.persons[index]=newP; //该操作没有改变persons本身,而灭有改变persons内部的结构,但没有更新界面 this.persons.splice(index,1,newP); } } }) </script>
更新之前效果如下:
更新之后的效果如下: