1. 程式人生 > 程式設計 >vue常用高階函式及綜合例項

vue常用高階函式及綜合例項

一. 常用的陣列的高階函式

假設,現在有一個數組,我們要對陣列做如下一些列操作

  1. 找出小於100的數字:
  2. 將小於100的數字,全部乘以2:
  3. 在2的基礎上,對所有數求和:

通常我們會怎麼做呢?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="app">
  <p>找出小於100的數字:</p>
  <p>將小於100的數字,全部乘以2: </p>
  <p>對所有數求和:</p>

  <button @click="getNum()">計算</button>
</div>

<script src="../
js
/vue.js"></script> <script> const app = new Vue({ el: "#app",data: { nums: [10,20,100,30,320,55,80,210],num1:0,num2:0,num3:0 },methods: { getNum(){ // 1. 找出<100的數字 let newNum1 = [] for(let num of this.nums) { if (num < 100) { newNum1.push(num) } } this.num1=newNum1 console.log(newNum1) // 2. 對小於100的數字*2 let newNum2 = [] for(let num of newNum1) { newNum2.push(num * 2) } this.num2 = newNum2 console.log(newNum2) // 3. 對小於100的數字*2後求和 let newNum3 = 0; for(let num of newNum2) { newNum3 += num } this.num3 = newNum3 console.log(newNum3) } } }) </script> </body> </html>

在上面的demo中,我們全部都是使用迴圈來進http://www.cppcns.com行計算,並且最後達到了我們想要的效果. 點選計算按鈕,檢視計算結果:

vue常用高階函式及綜合例項

在js高階函式裡面,有一些高階函式是可以直接計算得到上面的效果的. 下面主要介紹三個高階函式

  • filter
  • map
  • reduce

1. filter函式

filter()方法會建立一個新陣列,原陣列的每個元素傳入回撥函式中,回撥函式中有return返回值,若返回值為true,這個元素儲存到新陣列中;若返回值為false,則該元素不儲存到新陣列中;原陣列不發生改變。

  • 語法: array.filter(function(currentValue,index,arr),thisValue)
  • 引數

  vue常用高階函式及綜合例項

舉例1: 返回陣列中<100的元素

getNums() {
  // 來看看filter的用法   let num1 = [10,55. 80,210]
  let newNum1 = this.nums.filter(function (num) {
    return num < 100;
  })
  console.log(newNum1)
}
  • filter()函式的入參是一個function,出參是一個新的陣列
  • function函式也有參,這裡只傳入了第一個入參,表示: 迴圈遍歷時的陣列元素.
  • function的返回值型別是true或false,如果返回結果是true,則返回新陣列中有這個元素,返回結果是false,則返回新陣列中沒有這個元素

舉例2:利用filter,可以巧妙地去除Array的重複元素:

filter()接收的回撥函式,其GiccIhLr實可以有多個引數。通常我們僅使用第一個引數,表示Array的某個元素。回撥函式還可以接收另外兩個引數,表示元素的位置和陣列本身:

let nums = [10,210,320]
let newNum2 = this.nums.filter(function(element,self) {
  return self.indexOf(element) == index
})

執行結果

[10,210]

去除重複元素依靠的是indexOf總是返回第一個元素的位置,後續的重複元素位置與indexOf返回的位置不相等,因此被filter濾掉了。

2. map函式

方法返回一個新陣列,新陣列中的每一個元素為原始陣列對應每一個元素呼叫函式處理後的值;不會對空陣列進行編輯,不改變原來的陣列。

  • 語法:array.every(function(item,array){})
  • 引數:

    vue常用高階函式及綜合例項

舉例1: 求陣列中所有元素*2後的陣列

let nums = [10,320]
let newNum1 = this.nums.map(function (num)www.cppcns.com {
  return num * 2;
})

console.log(newNum1)

輸出結果:

[20,40,200,60GiccIhLr,640,110,160,420,640]

3. reduce函式

reduce() 方法接收一個函式作為累加器,reduce 為陣列中的每一個元素依次執行回撥函式,陣列中被刪除或從未被賦值的元素不處理.

  • 語法:arr.reduce(callback,[initiaGiccIhLrlValue])
  • 引數

vue常用高階函式及綜合例項

案例1: 求一個數組的和

// reduce的用法
let nums = [10,320]
let newNum1 = this.nums.reduce(function (total,num) {
  return num + total;
},0)
console.log(newNum1)

二. 綜合案例1

結合filter,map,reduce三個函式,獲取陣列中<100的元素,然後對這些元素同意*5,最後求*5後的所有元素的和

// reduce的用法
let nums = [10,320]
let newNum1 = this.nums.filter(function (number) {
  return number < 100
}).map(function (number) {
  return number * 5
}).reduce(function (total,0)
console.log(newNum1)

輸出結果: 1220

其實還有更簡單的演算法,lambda表示式

// reduce的用法
let nums = [10,320]
let newNum11 =
nums.filter(num => num < 100).map(num => num * 5,this).reduce((total,num) => total + num)
console.log(newNum11)

執行結果: 150

三.綜合案例2

顯示一個列表,選中那個那個變色,使用vue實現

vue常用高階函式及綜合例項

可以思考兩分鐘,看看,如何來設計.

在vue中,這個過程將非常簡單

  • 第一步: 定義了一個isCurrentIndex用來記錄當前選中元素的下標.
  • 第二步: 在class屬性中設定 :isCurrentIndex == index. 表示選中元素的下標顯示紅色,其他不顯示紅色.
  • 第三步: 定義一個click事件,每次點選事件,修改選中的下標值

程式碼如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .action {
      color: red;
    }
  </style>
</head>
<body>
<div id="app">
  <ul>
    <li v-for="(item,index) in languages" :class="{action:isCurrentIndex == index}" @click="changeCurrentIndex(index)"> {{index}}--{{item}}</li>
  </ul>
</div>

<script src="../js/vue.js"></script>
<script>
  var app = new Vue({
    el: "#app",data: {
      languages: ["java","php","python","go","c語言"],isCurrentIndex:0
    },methods: {
      changeCurrentIndex(index) {
        this.isCurrentIndex = index
      }
    }
  });
</script>
</body>
</html>

四. 綜合案例3

我們要做一個表格,具體內容如下

vue常用高階函式及綜合例項

主要有哪些東西呢?

  1. 有n本書,書有書名,出版日期,價格,數量,操作
  2. 價格保留兩位小數,數量可增減,最多減到0,
  3. 操作可以刪除表格,當表格沒有資料時顯示無資料
  4. 隨時計算總價格.

下面來看看這個程式碼如何實現,結合我們之前學過的js高階函式

第一步: 定義了n本書,放在vue的data屬性裡面

data: {
  books: [
    {name:"java設計模式",publishDate:"1998-10-21",price: 58.00,count: 1},{name:"go語言實戰分析",publishDate:"2018-5-12",price: 70.00,{name:"vue深入淺出",publishDate:"2019-08-09",price: 46.89,{name:"jquery實戰",publishDate:"2014-02-29",price: 39.98,count: 1}
  ],total: 0
},

定義了一個總價格,用來儲存計算後的總價格

第二步: 畫table

<div id="app">
  <table border="1">
    <thead>
      <tr>
        <td>序號</td>
        <td>書名</td>
        <td>出版日期</td>
        <td>價格</td>
        <td>購買數量</td>
        <td>操作</td>
      </tr>
    </thead>

    <tbody v-if="books.length==0">
      <tr>
        <td colspan="6" >沒有資料</td>
      </tr>
    </tbody>

    <tbody v-else>
      <tr v-for="(item,index) in books" >
        <td>{{index+1}}</td>
        <td>{{item.name}}</td>
        <td>{{item.publishDate}}</td>
        <td>{{item.price| priceUnit}} </td>
        <td>
          <button @click="sub(index)">-</button>
          {{item.count}}
          <button @click="add(index)">+</button>
        </td>
        <td>
          <button @click="del(index)">刪除</button>
      </tr>
    </tbody>
  </table>
  <label id="sum">總價: {{getTotal() | priceUnit}} </label>
</div>

在這裡我們迴圈遍歷了data資料,然後對價格進行了處理,增加了單位,對數量增加了增減的button. 最後定義了一個刪除功能

第三步. 使用過濾器格式化價格

在對價格進行格式化的時候,使用了管道符.這是過濾器的寫法. 不加過濾器之前,價格是58. 加了過濾器之後是: $58.00,增加了一個美元符號,價格保留兩位小數

因為不止有一個地方會用到加單位,所以,我們將其定義為一個方法. 如下寫法

filters: {
  priceUnit(price) {
    return "$" + price.toFixed(2)
  }
}

這裡定義了過濾器的寫法. 類似於methods. 裡面定義一個方法. 其實這個方法可不可以放在methods中呢? 也可以,但是放在filters有一個好處. 可以使用管道符寫法

<td>{{item.price | priceUnit}} </td>

使用過濾器,會自動將 | 前面的值作為引數傳遞給priceUnit

第四步: 定義methods,對圖書數量進行增減,且做少不能少於0

sub(index) {
  if (this.books[index].count <= 0) {
    this.books[index].coun = 0;
  } else {
    this.books[index].count --;
  }
},add(index) {
  this.books[index].count ++;
},

這個就不多說了,普通函式寫法

第五步: 計算總額

計算總額有多種寫法,常規寫法

getTotal() {
  let totalPrice = 0;
  for(let i = 0; i < this.books.length; i++) {

    totalPrice += this.books[i].price * this.books[i].count;
  }
  
  return totalPrice;
},

迴圈遍歷books,價格和數量乘積的和

推薦使用js的高階函式

getTotal() {
  // 使用陣列的高階函式計算每種書的價格總和
  return this.books.map((book)=>book.price * book.count).reduce((total,num) => total + num)
},

在回顧一下

map是對陣列的每一個元素執行操作

reduce是對陣列中所有元素求和

第六步: 刪除表格行

del(index){
  this.books.splice(index,1)
}

刪除行,使用splice刪除指定的data中的元素,就可以了

到此這篇關於vue常用高階函式及綜合案例的文章就介紹到這了,更多相關vue常用高階函式及例項內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!