按部就班VUE+Element 前端應用開發(7)--- 介紹一些常規的JS處理函數

在咱們使用VUE+Element 處理界面的時候,每每碰到須要利用JS集合處理的各類方法,如Filter、Map、reduce等方法,也能夠涉及到一些對象屬性賦值等常規的處理或者遞歸的處理方法,之前對於這些不是很在乎,但每每真正使用的時候,須要瞭解清楚,不然很容易腦殼出現短路的狀況。本篇隨筆列出一些在VUE+Element 前端開發中常常碰到的JS處理場景,供參考學習。前端

一、常規集合的filter、map、reduce處理方法

filter函數的主要用途是對數組元素進行過濾,並返回一個符合條件的元素的數組vue

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

輸出:[10,20,30]node

 

map函數是對數組每一個元素的映射操做,並返回一個新數組,原數組不會改變將newNums中每一個數字乘2數組

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

輸出:[20,40,60,222,666]服務器

 

reduce函數主要用於對數組全部元素的彙總操做,如所有相加、相乘等async

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

輸出:726函數

 

有時候能夠結合幾種處理方式一塊兒,以下綜合案例所示。學習

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)

結果:120ui

 

一樣咱們也能夠在vue裏面,利用require.context的處理機制,遍歷文件進行處理,也須要用到了filter,以下代碼所示。this

下面代碼是我對某個文件夾裏面的文件進行一個過濾處理操做

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

 

二、遞歸處理

有時候,咱們須要從一個JSON集合裏面,因爲集合是嵌套的,如children裏面還有chilren集合,根據某個關鍵屬性進行查詢,這種處理方式就要用到遞歸了。

例如我定義的一個菜單集合裏面,就是這樣一個嵌套的結構,須要根據名稱來得到對應的對象的時候,就涉及到了一個遞歸處理函數。

首先咱們來看看菜單的JSON集合。

// 此菜單數據通常由服務器端返回
export const asyncMenus = [
  {
    id: '1',
    pid: '-1',
    text: '首頁',
    icon: 'dashboard',
    name: 'dashboard'
  },
  {
    id: '2',
    pid: '-1',
    text: '產品信息',
    icon: 'table',
    children: [
      {
        id: '2-1',
        pid: '2',
        text: '產品展現',
        name: 'product-show',
        icon: 'table'
      }]
  },
  {
    id: '3',
    pid: '-1',
    text: '雜項管理',
    icon: 'example',
    children: [
      {
        id: '3-1',
        pid: '3',
        text: '圖標管理',
        name: 'icon',
        icon: 'example'
      },
      {
        id: '3-3',
        pid: '3',
        text: '樹功能展現',
        name: 'tree',
        icon: 'tree'
      },
      {
        id: '3-2',
        pid: '3',
        text: '二級菜單2',
        icon: 'tree',
        children: [
          {
            id: '3-2-2',
            pid: '3-2',
            text: '三級菜單2',
            name: 'menu1-1',
            icon: 'form'
          }
        ]
      }
    ]
  }
]

若是咱們須要根據ID來遍歷查詢,就是一個典型的遞歸查詢處理。

    // 根據菜單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) { // 只有找到才返回
            return foundItem
          }
        }
      }
    }

這裏值得注意的是,不能在遞歸的時候,使用下面直接返回

 
 
return this.FindMenuById(item.children, menuid)

而須要判斷是否有結果在進行返回,不然嵌套遞歸就可能返回undefined類型

  var foundItem = this.FindMenuById(item.children, menuid)
  if (foundItem) { // 只有找到才返回
    return foundItem
  }

 

三、forEach遍歷集合處理

在不少場合,咱們也須要對集合進行一個forEach的遍歷處理,以下根據它的鍵值進行處理,註冊全局過濾器的處理操做

// 導入全局過濾器
import * as filters from './filters'
// 註冊全局過濾器
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

或者咱們在經過API方式獲取數據後,對集合進行處理的操做

    // 獲取產品類型,用於綁定字典等用途
    GetProductType().then(data => {
      if (data) {
        this.treedata = [];// 樹列表清空
        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)
        })

        // 獲取列表信息
        this.getlist()
      }
    });

又或者請求字典數據的時候,進行一個非空值的判斷處理。

      // 使用字典類型,從服務器請求數據
      GetDictData(this.typeName).then(data => {
        if (data) {
          data.forEach(item => {
            if (item && typeof (item.Value) !== 'undefined' && item.Value !== '') {
              that.dictItems.push(item)
            }
          });
        }
      })

 

四、Object.assign賦值方法

在有些場合,咱們須要把全新的集合,複製到另外一個對象上,替換原來對象的屬性值,那麼咱們能夠利用Object對象的assign方法。

如在編輯界面展現的時候,把請求到的對象屬性複製到表單對象上。

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

或者查詢的時候,得到查詢條件,進行部分替換

      // 構造常規的分頁查詢條件
      var param = {
        type: this.producttype === 'all' ? '' : this.producttype,
        pageindex: this.pageinfo.pageindex,
        pagesize: this.pageinfo.pagesize
      };

      // 把SearchForm的條件加入到param裏面,進行提交查詢
      param.type = this.searchForm.ProductType // 轉換爲對應屬性
      Object.assign(param, this.searchForm);

 

五、slice() 方法

slice() 方法可從已有的數組中返回選定的元素。

語法以下所示。

arrayObject.slice(start,end)

以下案例所示。

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

或者咱們結合filter函數對圖標集合進行獲取部分處理

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;
  }
}
相關文章
相關標籤/搜索