Conventional JS processing functions for Vue Element front-end application development

Conventional JS processing functions for Vue Element front-end application development

1. Filter, map, and reduce processing methods for conventional collections

The main purpose of the filter function is to filter array elements and return an array of elements that meet the conditions.

const nums = [10,20,30,111,222,333]
let newNums = nums.filter(function(n){
    return n<100
})

Output:

[10,20,30]

The map function maps each element of the array and returns a new array. The original array will not be changed. Multiply each number in newNums by 2.

const nums = [10,20,30,111,222,333]
let newNums = nums.map(function(n){
    return n*2
})

Output:

[20,40,60,222,666]

The reduce function is mainly used to summarize all elements of an array, such as adding and multiplying them.

const nums = [10,20,30,111,222,333]
let newNums = nums.reduce(function(preValue,n){
    return PreValue+n
},0)

Output:

726

Sometimes several treatments can be combined, as shown in the following comprehensive case.

const nums = [10,20,30,111,222,333]
let newNums = nums.filter(function(n){
    return n<100
}).map(function(n){
    return n*2
}).reduce(function(preValue,n){
    return preValue+n
},0)

result:

120

There is also a find method for array collections, which is similar to the filter method.

The find() method is mainly used to return the first element in the array that meets the conditions (if there is no element, it returns undefined)

var Array = [1,2,3,4,5,6,7];
 var result = Array.find(function(value){
     return value > 5; //condition});
 console.log(result); //6
 console.log(Array); //[1,2,3,4,5,6,7]

Similarly, we can also use the processing mechanism of require.context in vue to traverse files for processing, and we also need to use filter, as shown in the following code.

The following code is a filtering operation I perform on the files in a folder

const req = require.context('vue-awesome/icons', true, /\.js$/)
const requireAll = requireContext => requireContext.keys()

const re = /\.\/(.*)\.js/

const vueAwesomeIcons = requireAll(req).filter((key) => { return key.indexOf('index.js') < 0 }).map(i => {
  return i.match(re)[1]
})

export default vueAwesomeIcons

2. Recursive processing

Sometimes, we need to query a JSON collection based on a key attribute because the collection is nested, such as children, which contains a chilren collection. This processing method requires recursion.

For example, in a menu collection I defined, there is such a nested structure. When it is necessary to obtain the corresponding object according to the name, a recursive processing function is involved.

First let's take a look at the menu's JSON collection.

// This menu data is generally returned by the server export const asyncMenus = [
  {
    id: '1',
    pid: '-1',
    text: 'Homepage',
    icon: 'dashboard',
    name: 'dashboard'
  },
  {
    id: '2',
    pid: '-1',
    text: 'Product Information',
    icon: 'table',
    children: [
      {
        id: '2-1',
        pid: '2',
        text: 'Product Display',
        name: 'product-show',
        icon: 'table'
      }]
  },
  {
    id: '3',
    pid: '-1',
    text: 'Miscellaneous Management',
    icon: 'example',
    children: [
      {
        id: '3-1',
        pid: '3',
        text: 'Icon Management',
        name: 'icon',
        icon: 'example'
      },
      {
        id: '3-3',
        pid: '3',
        text: 'Tree function display',
        name: 'tree',
        icon: 'tree'
      },
      {
        id: '3-2',
        pid: '3',
        text: 'Secondary Menu 2',
        icon: 'tree',
        children: [
          {
            id: '3-2-2',
            pid: '3-2',
            text: 'Level 3 menu 2',
            name: 'menu1-1',
            icon: 'form'
          }
        ]
      }
    ]
  }
]

If we need to traverse the query based on the ID, it is a typical recursive query processing.

// Get the corresponding menu object according to the menu id FindMenuById(menuList, menuid) {
      for (var i = 0; i < menuList.length; i++) {
        var item = menuList[i];
        if (item.id && item.id === menuid) {
          return item
        } else if (item.children) {
          var foundItem = this.FindMenuById(item.children, menuid)
          if (foundItem) { // Only return foundItem if found
          }
        }
      }
    }

It is worth noting here that you cannot use the following direct return when recursing.

return this.FindMenuById(item.children, menuid)

It is necessary to determine whether there is a result being returned, otherwise the nested recursion may return the undefined type.

var foundItem = this.FindMenuById(item.children, menuid)
  if (foundItem) { // Only return foundItem if found
  }

3. forEach traversal collection processing

In many cases, we also need to perform a forEach traversal on the collection, as follows: process it according to its key value and register the processing operation of the global filter

// Import global filters import * as filters from './filters'
// Register global filterObject.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

Or we process the collection after obtaining data through the API

// Get the product type for binding dictionaries, etc. GetProductType().then(data => {
      if (data) {
        this.treedata = []; // Clear the tree list data.forEach(item => {
          this.productTypes.set(item.id, item.name)
          this.typeList.push({ key: item.id, value: item.name })

          var node = { id: item.id, label: item.name }
          this.treedata.push(node)
        })

        // Get list information this.getlist()
      }
    });

Or when requesting dictionary data, perform a non-empty value judgment.

// Use the dictionary type to request data from the server GetDictData(this.typeName).then(data => {
        if (data) {
          data.forEach(item => {
            if (item && typeof (item.Value) !== 'undefined' && item.Value !== '') {
              that.dictItems.push(item)
            }
          });
        }
      })

The forEach() method is also used to execute a callback function once for each element in the array, but it has no return value (or its return value is undefined, even if we write a return statement in the callback function, the return value is still undefined)

Note: If there are two parameters in forEach, the first parameter is the element in the collection, and the second parameter is the index of the collection;

4. Object.assign assignment method

In some cases, we need to copy a new collection to another object and replace the property values ​​of the original object. In this case, we can use the assign method of the Object object.

For example, when the editing interface is displayed, the requested object properties are copied to the form object.

var param = { id: id }
GetProductDetail(param).then(data => {
	Object.assign(this.editForm, data);
})

Or when querying, get the query conditions and perform partial replacement

// Construct regular paging query conditions var param = {
        type: this.producttype === 'all' ? '' : this.producttype,
        pageindex: this.pageinfo.pageindex,
        pagesize: this.pageinfo.pagesize
      };

      // Add the SearchForm conditions to param and submit the query param.type = this.searchForm.ProductType // Convert to the corresponding attribute Object.assign(param, this.searchForm);

5. slice() method

The slice() method returns selected elements from an existing array.

The syntax is as follows.

arrayObject.slice(start,end)

As shown in the following case.

let red = parseInt(color.slice(0, 2), 16)
let green = parseInt(color.slice(2, 4), 16)
let blue = parseInt(color.slice(4, 6), 16)

Or we can combine the filter function to obtain part of the icon collection

vueAwesomeIconsFiltered: function() {
  const that = this
  var list = that.vueAwesomeIcons.filter(item => { return item.indexOf(that.searchForm.label) >= 0 })
  if (that.searchForm.pagesize > 0) {
    return list.slice(0, that.searchForm.pagesize)
  } else {
    return list;
  }
}

The above is the details of the conventional JS processing functions of Vue Element front-end application development. For more information about Vue Element's conventional JS processing functions, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • element-plus a vue3.x UI framework (first experience with element-ui 3.x version)
  • Use vue3.x+vite+element-ui+vue-router+vuex+axios to build a project
  • Detailed explanation of various ways to use element-plus in Vue3.x

<<:  Detailed explanation of Linux copy and paste in VMware virtual machine

>>:  Linux solves the problem that Deepin cannot start Google Chrome browser as root user

Recommend

Zen coding for editplus example code description

For example, he enters: XML/HTML Code div#page>...

Use of Linux telnet command

1. Introduction The telnet command is used to log...

MySQL table auto-increment id overflow fault review solution

Problem: The overflow of the auto-increment ID in...

Several ways to easily traverse object properties in JS

Table of contents 1. Self-enumerable properties 2...

Nodejs global variables and global objects knowledge points and usage details

1. Global Object All modules can be called 1) glo...

How to build your own Nexus private server in Linux

This article describes how to build a Nexus priva...

The front-end page pop-up mask prohibits page scrolling

A problem that front-end developers often encount...

FastDFS and Nginx integration to achieve code analysis

FastDFS & Nginx Integration: The tracker is c...

Demystifying the HTML 5 Working Draft

The World Wide Web Consortium (W3C) has released a...

Vue implements button switching picture

This article example shares the specific code of ...

Table related arrangement and Javascript operation table, tr, td

Table property settings that work well: Copy code ...

Javascript operation mechanism Event Loop

Table of contents 1. Four concepts 1. JavaScript ...

Example of building a Jenkins service with Docker

Pull the image root@EricZhou-MateBookProX: docker...