1. 程式人生 > >Vue常用指令

Vue常用指令

vue.js utf-8 java return lse Once bin func 表達式

引言:vue 的一些常用指令(逐步更新)。

v-if 條件
v
-else 與v-if 搭配使用 v-else-if 與v-if 搭配使用
v
-show 顯示與隱藏 v-for 循環 v-model 雙向綁定數據 v-bind 屬性綁定 語法糖“ : ”
v
-on 事件 語法糖“ @ ”
v
-text讀取文本 ps :不能讀取html標簽 v-html 能讀取html標簽 v-class 類名 v-style 樣式 v-once 只渲染一次(只執行一次) v-cloak 防閃爍(解決初始化慢導致頁面閃動) v
-pre 把標簽內部的元素原位輸出,比如無視“{{}}”

Vue 初試,一個商品列表:

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>vue 購物車初試</title>
  6     <script type="text/javascript"src="js/vue.js"></script>
  7
<style type="text/css"> 8 9 [v-cloack]{ 10 display: none; /*防止屏幕閃動*/ 11 } 12 table{ 13 border: 1px solid greenyellow; 14 border-spacing: 5px; 15 empty-cells: show; 16 } 17 th,td{ 18
padding: 8px 16px; 19 border: 1px solid green; 20 text-align: left; 21 } 22 th{ 23 background-color: #f7f7f7; 24 color: #5c6b77; 25 white-space: nowrap; 26 } 27 .main{ 28 width: 500px; 29 height: 500px; 30 margin: 50px auto; 31 } 32 33 34 </style> 35 </head> 36 <body> 37 <div class="app" v-cloak> 38 <div class="main"> 39 <template v-if="list.length"> 40 <table> 41 <thead> 42 <tr> 43 <th></th> 44 <th>商品名稱</th> 45 <th>商品單價</th> 46 <th>購買數量</th> 47 <th>操作</th> 48 </tr> 49 </thead> 50 <tbody> 51 <tr v-for="(item,index) in list"> <!--v-for 循環商品列表--> 52 <td>{{index+1}}</td><!-- 下標從0開始,但是序號從1,所以+1--> 53 54 <td>{{item.name}}</td> <!--商品名字--> 55 56 <td>{{item.price}}</td> <!--商品價格--> 57 58 <td><button @click="red(index)":disabled="item.count===1">-</button> <!--減少商品函數,同時綁定disable屬性,如果商品數量==1 時失效--> 59 60 {{item.count}} 61 <button @click="add(index)">+</button> <!--增加商品--> 62 </td> 63 <td> 64 <button @click="rem(index)">移除</button> <!--移除商品--> 65 </td> 66 </tr> 67 </tbody> 68 </table> 69 <div>總價:¥{{totalPrice}}</div> <!--總價--> 70 </template> 71 <div v-else>購物車空</div> 72 </div> 73 </div> 74 <script type="text/javascript"> 75 var app=new Vue({ 76 el:‘.app‘, 77 data:{ 78 list:[ 79 { 80 id:1, 81 name:‘iphone7‘, 82 price:‘5000‘, 83 count:1 84 }, 85 { 86 id:2, 87 name:‘ipad‘, 88 price:‘6000‘, 89 count:2 90 }, 91 { 92 id:3, 93 name:‘ip7‘, 94 price:‘600‘, 95 count:1 96 } 97 ] 98 }, 99 computed:{ 100 totalPrice:function () { 101 var total=0; 102 for (var i=0;i<this.list.length;i++){ 103 var item=this.list[i]; 104 total+=item.price*item.count; 105 } 106 return total.toString().replace(/\B(?=(\d{3})+$)/g,‘,‘); //正則表達式,將總價格以千位輸出(每三位添加一個逗號) 107 } 108 }, 109 methods:{ 110 red:function (index) { 111 if (this.list[index].count===1)return; //如果商品數量為1函數停止 ,雖然有上面的disabled控制,但是添加這個可以增加可靠性 112 this.list[index].count--; 113 }, 114 add:function (index) { 115 this.list[index].count++; //增加商品量 116 }, 117 rem:function (index) { 118 this.list.splice(index,1); //移除商 spilce 函數:可刪除從 index 處開始的零個或多個元素 119 } 120 } 121 }) 122 </script> 123 </body> 124 </html>

您可以 : 點擊這裏查看效果

Vue常用指令