Vue commonly used high-order functions and comprehensive examples

Vue commonly used high-order functions and comprehensive examples

1. Commonly used high-order functions of arrays

Suppose, now there is an array, and we want to perform the following operations on the array

  1. Find the number less than 100:
  2. Multiply all numbers less than 100 by 2:
  3. On the basis of 2, sum all the numbers:

What do we usually do?

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
</head>
<body>
<div id="app">
 <p>Find a number less than 100:</p>
 <p>Multiply all numbers less than 100 by 2: </p>
 <p>Sum all numbers:</p>

 <button @click="getNum()">Calculate</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. Find a number < 100 let newNum1 = []
    for(let num of this.nums) {
     if (num < 100) {
      newNum1.push(num)
     }
    }
    this.num1=newNum1
    console.log(newNum1)


    // 2. For numbers less than 100 * 2
    let newNum2 = []
    for(let num of newNum1) {
     newNum2.push(num * 2)
    }
    this.num2 = newNum2
    console.log(newNum2)

    // 3. Sum the numbers less than 100 * 2 let newNum3 = 0;
    for(let num of newNum2) {
     newNum3 += num
    }
    this.num3 = newNum3
    console.log(newNum3)
   }
  }
 })
</script>
</body>
</html>

In the above demo, we all use loops to perform calculations, and finally achieve the desired effect. Click the calculation button to view the calculation results:

In js high-order functions, some high-order functions can directly calculate the above effects. The following mainly introduces three high-order functions

  • filter
  • map
  • reduce

1. Filter function

The filter() method creates a new array. Each element of the original array is passed to the callback function. The callback function has a return value. If the return value is true, the element is saved in the new array. If the return value is false, the element is not saved in the new array. The original array does not change.

  • Syntax: array.filter(function(currentValue,index,arr), thisValue)
  • parameter

Example 1: Return the elements in the array that are less than 100

getNums() {
 // Let's see how to use the filter let num1 = [10, 20, 100, 30, 320, 55. 80, 210]
 let newNum1 = this.nums.filter(function (num) {
  return num < 100;
 })
 console.log(newNum1)
}
  • The input parameter of the filter() function is a function, and the output parameter is a new array
  • The function also has parameters, and here only the first parameter is passed in, which means: the array element when looping.
  • The return value type of the function is true or false. If the return result is true, it means that the element is in the new array. If the return result is false, it means that the element is not in the new array.

Example 2: Using filter, you can cleverly remove duplicate elements from an Array:

The callback function received by filter() can actually have multiple parameters. Usually we only use the first parameter, which represents an element of the Array. The callback function can also receive two additional parameters, indicating the position of the element and the array itself:

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

Operation Results

[10, 20, 100, 30, 320, 55, 80, 210]

Removing duplicate elements relies on the fact that indexOf always returns the position of the first element. The positions of subsequent duplicate elements are not equal to the position returned by indexOf, so they are filtered out by the filter.

2. Map Function

The method returns a new array, each element of which is the value of the original array after calling the function on each element; the empty array will not be edited and the original array will not be changed.

  • Syntax: array.every(function(item,index,array){})
  • parameter:

Example 1: Find the array after all elements in the array are multiplied by 2

let nums = [10, 20, 100, 30, 320, 55, 80, 210, 20, 55, 320]
let newNum1 = this.nums.map(function (num) {
 return num * 2;
})

console.log(newNum1)

Output:

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

3. Reduce function

The reduce() method receives a function as an accumulator. Reduce executes the callback function for each element in the array in turn. Elements in the array that have been deleted or never assigned a value are not processed.

  • Syntax: arr.reduce(callback,[initialValue])
  • parameter

Example 1: Find the sum of an array

// usage of reduce let nums = [10, 20, 100, 30, 320, 55, 80, 210, 20, 55, 320]
let newNum1 = this.nums.reduce(function (total, num) {
 return num + total;
}, 0)
console.log(newNum1)

2. Comprehensive Case 1

Combine the three functions of filter, map, and reduce to get the elements in the array that are less than 100, then multiply these elements by *5, and finally find the sum of all the elements after *5.

// usage of reduce let nums = [10, 20, 100, 30, 320, 55, 80, 210, 20, 55, 320]
let newNum1 = this.nums.filter(function (number) {
 return number < 100
}).map(function (number) {
 return number * 5
}).reduce(function (total, num) {
 return num + total;
}, 0)
console.log(newNum1)

Output: 1220

In fact, there is a simpler algorithm, lambda expression

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

Execution result: 150

3. Comprehensive Case 2

Display a list, select the one that changes color, use vue to implement

Think about it for two minutes and see how to design it.

In Vue, this process will be very simple

  • Step 1: Define an isCurrentIndex to record the index of the currently selected element.
  • Step 2: Set isCurrentIndex == index in the class attribute. This means the subscript of the selected element is displayed in red, and the others are not displayed in red.
  • Step 3: Define a click event, and modify the selected index value each time the event is clicked

The code is as follows:

<!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 language"],
   isCurrentIndex:0
  },
  methods: {
   changeCurrentIndex(index) {
    this.isCurrentIndex = index
   }
  }
 });
</script>
</body>
</html>

IV. Comprehensive Case 3

We need to make a table with the following contents:

What are the main things?

  1. There are n books, each book has a title, publication date, price, quantity, and operation.
  2. The price is rounded to two decimal places, the quantity can be increased or decreased, and the maximum reduction is 0.
  3. The operation can delete the table. When the table has no data, it will display "No data"
  4. Calculate total price at any time.

Let's take a look at how this code is implemented, combined with the js high-order functions we learned before

Step 1: Define n books and put them in the data attribute of vue

data: {
 books:
  {name:"java design pattern", publishDate:"1998-10-21", price: 58.00, count: 1},
  {name:"Go Language Practical Analysis", publishDate:"2018-5-12", price: 70.00, count: 1},
  {name:"vue is easy to understand", publishDate:"2019-08-09", price: 46.89, count: 1},
  {name:"jquery in action", publishDate:"2014-02-29", price: 39.98, count: 1}
 ],
 total: 0
},

Defines a total price to save the calculated total price

Step 2: Draw the table

<div id="app">
 <table border="1">
  <thead>
   <tr>
    <td>Serial number</td>
    <td>Book Title</td>
    <td>Publication Date</td>
    <td>Price</td>
    <td>Purchase quantity</td>
    <td>Operation</td>
   </tr>
  </thead>

  <tbody v-if="books.length==0">
   <tr>
    <td colspan="6" >No data</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)">Delete</button>
   </tr>
  </tbody>
 </table>
 <label id="sum">Total price: {{getTotal() | priceUnit}} </label>
</div>

Here we loop through the data, process the price, add units, and add buttons to increase and decrease the quantity. Finally, we define a delete function.

Step 3. Format the price using filters

When formatting the price, the pipe character is used. This is how the filter is written. Before the filter, the price is 58. After the filter is added, it is: $58.00, with a dollar sign added and the price is rounded to two decimal places.

Because adding units is used in more than one place, we define it as a method.

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

Here is the definition of how to write a filter. It is similar to methods. A method is defined in it. In fact, can this method be placed in methods? Yes, but there is an advantage of putting it in filters. You can use the pipe character to write it.

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

Using the filter, the value before | will be automatically passed as a parameter to priceUnit

Step 4: Define methods to increase or decrease the number of books, and the number cannot be less than 0

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

I won't say much about this, ordinary function writing

Step 5: Calculate the total amount

There are many ways to calculate the total amount. The conventional way is

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

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

Loop through books, sum of price and quantity multiplied by

It is recommended to use js's high-order functions

getTotal() {
 // Use higher-order functions on arrays to calculate the total price of each book return this.books.map((book)=>book.price * book.count).reduce((total,num) => total + num)
},

In review

Map performs an operation on each element of an array.

Reduce is to sum all the elements in the array

Step 6: Delete table rows

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

To delete a row, use splice to delete the elements in the specified data.

This is the end of this article about Vue's commonly used high-order functions and comprehensive cases. For more relevant Vue's commonly used high-order functions and examples, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of Vue array responsive operations and high-order function usage code
  • Based on vue-simple-uploader, encapsulate the global upload plug-in function of file segment upload, instant upload and breakpoint resume
  • How to use vite to build vue3 application
  • Detailed explanation of Vue3.0 + TypeScript + Vite first experience

<<:  Detailed explanation of the construction and use of docker private warehouse

>>:  Commonplace talk about MySQL event scheduler (must read)

Recommend

Complete step record of vue encapsulation TabBar component

Table of contents Implementation ideas: Step 1: C...

Vue implements internationalization of web page language switching

1. Basic steps 1: Install yarn add vue-i18n Creat...

Linux uses if to determine whether a directory exists.

How to use if in Linux to determine whether a dir...

Three BOM objects in JavaScript

Table of contents 1. Location Object 1. URL 2. Pr...

Detailed explanation of CSS3 animation and new features of HTML5

1. CSS3 animation ☺CSS3 animations are much easie...

Detailed summary of MySQL and connection-related timeouts

MySQL and connection related timeouts Preface: To...

HTML meta explained

Introduction The meta tag is an auxiliary tag in ...

Bundling non-JavaScript static resources details

Table of contents 1. Custom import in packaging t...

Solutions to Mysql index performance optimization problems

The optimization created by MySQL is to add index...

js dynamically implements table addition and deletion operations

This article example shares the specific code for...

Detailed explanation of CocosCreator Huarongdao digital puzzle

Table of contents Preface text 1. Panel 2. Huaron...

Install redis and MySQL on CentOS

1|0MySQL (MariaDB) 1|11. Description MariaDB data...