Element input box with history query record

Keywords: Javascript JSON Attribute Vue

Requirement description

Add the query box on the page to display the history search record

Realization and pit record

Use the Element input box with input suggestions to achieve this requirement. Usage details Official website

1. Pit 1: cannot return array directly in querySearch, must call callback function cb to process data

Take a look at the example below. The suggested list should be an array. Then I directly returned an array in querySearch:

 querySearch(queryString, cb) {
    return JSON.parse(localStorage.getItem('srcOrderNoArr'))
  },

But when I went back to the web page, I found that the list data could not be loaded

Correct posture:

 /**
 * Suggestion list
 */
querySearch(queryString, cb) {
  // Call callback to return the data of suggestion list
  cb(JSON.parse(localStorage.getItem('srcOrderNoArr')))
}
2. Pit 2: the data format in the array is required. The format must be [{value: '', xxx: ''}, {value: '', xxx: ''},...]

The recommended list is rendered according to the value attribute value in the array, so the objects in the array must have value key value pairs. For example:

data () {
    return {
        srcOrderNoArr: [{
            value: '',  // This must have
            type: ''
        },
        {
            value: '',
            type: ''
        },
        {
            value: '',
            type: ''
        }]
   }
}
methods: {
    /**
     * Store search records in localStorage
     */
    setIntoStorage (type) {
      let self = this
      let noArr = [],  // Order number history array
        text = '', value = ''
      switch (type) {
        case 'srcOrderNo':
          text = 'srcOrderNoArr'
          value = self.srcOrderNo
          break
        case 'jobOrderNo':
          text = 'jobOrderNoArr'
          value = self.jobOrderNo
          break
        case 'cntNo':
          text = 'cntNoArr'
          value = self.cntNo
          break
        default:
          break
      }
      noArr.push({value: value, type: type})
      if(JSON.parse(localStorage.getItem(text))) {  // Determine whether there is localStorage for xxx query record
        if(localStorage.getItem(text).indexOf(value) > -1 ) {  // Determine whether this query record exists. If it exists, it does not need to be stored again
          return
        }
        if(JSON.parse(localStorage.getItem(text)).length >= 5) {
          let arr = JSON.parse(localStorage.getItem(text))
          arr.pop()
          localStorage.setItem(text, JSON.stringify(arr))
        }
        localStorage.setItem(text, JSON.stringify(noArr.concat(JSON.parse(localStorage.getItem(text)))))
      }
      else {  // First created
        localStorage.setItem(text, JSON.stringify(noArr))
      }
    }
}

Reference resources

  1. Using localStorage to store information in vue
  2. Element UI input box with input suggestions

Posted by Concat on Fri, 06 Dec 2019 00:26:58 -0800