前端框架之Vue學習(二)

一、事件修飾符
enter:回車生效(常用於替代判斷是否按下回車事件)
once:單次生效(只會生效一次)
stop:阻止事件冒泡
self:阻止事件冒泡(只有點擊自身時才生效)
capture:將後面的事件變爲捕獲事件
prevent:阻止默認事件(比如:a標籤之類的)
二、axios的使用
Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。

Axios 在Vue中的使用

1  <div id="app"></div>
2  	<script src="node_modules/vue/dist/vue.js"></script>
3  	<!-- 基於promise的 -->
4  	<script src="node_modules/axios/dist/axios.js"></script>
5  	<script>
6  		let vm = new Vue({
7  			el: "#app",
8  			// 數據被初始化後會進行調用,this只想vm實例,鉤子函數。
9  			created() {
10  				// var that = this;
11  				this.getData();
12  			},
13  			method: {
14  				getData() {
15  					axios.get("./carts.json").then(res=> {
16  						// console.log(res);
17  						this.products = res.data;
18  					}, err=> {
19  
20  					});
21  				}
22  			},
23  			data: {
24  				products: []
25  			}
26  		})
27	</script>

三、購物車案例
(1) 使用axios並展示到view中

//VM實例創建後會自動執行這個函數
created() {
// 這裏使用箭頭函數,會使得this指向vue的實例對象
            axios.get("./book.json").then((data) => {
                this.bookList = data.data;
            })
        },

(2)v-bind
使用v-bind將對象綁定到dom屬性上(v-bind:src === :src)

<img :src="item.imgUrl" alt="">

(3) v-model.number

<input type="number" v-model="item.number" min="1">

(4)實現刪除功能

delBook(index) {
                this.bookList = this.bookList.filter((item, suo) => {
                    return suo != index;
                })
            },

(5)實現全選和反選

selectAll() {
                this.bookList.forEach((item) => {
                    item.isSelect = this.isAll;
                })
            },

(6)單個選項影響全選按鈕

 selectOne() {
                this.isAll = this.bookList.every((item) => {
                    return item.isSelect == true;
                })
            },

(7)實現計算總價功能

priceNum() {
                return this.bookList.reduce((num, item) => {
                    if (item.isSelect) {
                        num += parseFloat((item.price * item.number));
                        return num;
                    } else {
                        return num;
                    }
                },0)
            }

注意:在這個案例中使用函數表達式時會有一些缺陷,當整個頁面中有值發生變化時,都會影響計算函數的執行。所以引入兩個概念:過濾器和computed(自動計算屬性)
四、filters過濾器
Vue中過濾器有兩種定義方式(1)全局定義(2)局部定義

//全局定義
Vue.filter('myfilter',function(val){
return val;
//返回處理過的值
}
)
//局部定義
4  filters: {
5  		toFixed(input, param1) {
6  			return '¥' + input.toFixed(param1);
7  		}
8  }

computed使用示例

computed: {
        // 這裏面寫函數,這個函數就是數據模型!!!
        total() {
          console.log("總價重新進行了計算")
            return this.bookList.reduce((total, item)=> {
              if(item.isSelect) {
                // 加入到total
                total += parseFloat((item.price * item.number))
                return total;
              }else {
                return total;
              }
            }, 0)
        },
        isAll: {
          get() {
            return this.bookList.every((item)=> {
              return item.isSelect == true;
            })
          },
          set(newVal) {
            this.bookList.forEach((item)=> {
              item.isSelect = newVal
            })
          }  
        }
      },

自動計算屬性,一旦依賴的數據模型發生變化就會重新執行代碼
自動計算屬性不支持異步代碼!!!

案例源碼:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <div class="container">
      <table class="table table-bordered table-hover">
        <tr>
          <th>
            全選
            <input type="checkbox" v-model="isAll">
          </th>
          <th>商品</th>
          <th>單價</th>
          <th>數量</th>
          <th>小計</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in bookList">
          <td>
            <input type="checkbox" v-model="item.isSelect">
          </td>
          <td>
            <img :src="item.imgUrl" alt="">
            <span>{{item.title}}</span>
          </td>
          <td>
            <span>{{item.price}}</span>
          </td>
          <td>
            <input type="number" v-model="item.number" min="1">
          </td>
          <td>
            <span>¥{{(item.number*item.price).toFixed(2)}}</span>
            <span>¥{{(item.number*item.price) | toFixed(2)}}</span>
          </td>
          <td>
            <button class="btn btn-danger" @click="deletePro(index)">刪除</button>
          </td>
        </tr>
        <tr>
          <!-- 在{{}} 可以使用表達式-->
          <td>總價:{{total.toFixed(2)}}</td>
        </tr>
      </table>
    </div>
  </div>
  <script src="node_modules/vue/dist/vue.min.js"></script>
  <script src="node_modules/axios/dist/axios.min.js"></script>
  <script>
    var vm = new Vue({
      el:"#app",
      created() {
        // 這個vm實例創建之後會自動執行這個函數。
        axios.get("./book.json").then((data)=> {
          console.log(data.data)
          // 將獲取到的數據賦值給booklist
          this.bookList = data.data
        })
      },
      data: {
        bookList: [],
        msg: "je"
      },
      computed: {
        // 這裏面寫函數,這個函數就是數據模型!!!
        // 自動計算屬性: 一旦依賴的數據模型發生變化就會重新執行邏輯
        // 自動計算屬性不支持異步代碼!!!
        total() {
          console.log("總價重新進行了計算")
            return this.bookList.reduce((total, item)=> {
              if(item.isSelect) {
                // 加入到total
                total += parseFloat((item.price * item.number))
                return total;
              }else {
                return total;
              }
            }, 0)
        },
        isAll: {
          get() {
            return this.bookList.every((item)=> {
              return item.isSelect == true;
            })
          },
          set(newVal) {
            this.bookList.forEach((item)=> {
              item.isSelect = newVal
            })
          }
          
        }
      },
      methods: {
        // 單獨選中一個產品
        // selectOne(){
        //   // every方法當所有的item滿足條件時返回true,一個不滿足返回false
        //   this.isAll = this.bookList.every((item)=> {
        //     return item.isSelect == true;
        //   })
        // },
		filters: {
  		toFixed(input, param1) {  	
  				return '¥' + input.toFixed(param1);
 				}
		 },

        // 刪除商品
        deletePro(ind) {
          // 使用filter進行刪除操作,過濾掉不滿足條件的數據
          this.bookList = this.bookList.filter((item, index)=> {
            return index != ind;
          })
        }
      }
    })
  </script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章