This is the 26th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

[thousands of words long, stay up late to update, original is not easy, a lot of support, thank you]

preface

Hello, everyone. Today we continue to improve our questionnaire function. Yesterday, we added the data validity check function to the questionnaire. From the questionnaire topic configuration to the validity check of the questionnaire data to the storage and submission of the questionnaire, the whole questionnaire system has taken shape and gradually improved, but it still lacks many functions, such as login by role, background management, submission record display and so on. Don’t worry, since this is a step-by-step series we’ll take it one step at a time. Today will realize the questionnaire submission record saving and display function.

Save the submission record

In order to facilitate the operation, we do not use the background database, still use the localStorage localStorage for the preservation of historical records, which is divided into three steps:

  • First, let’s analyze the information we want to save:
    • The unique identification field ID of the submission record, the title of the submission record, the user who filled in the questionnaire, the submission time, and the specific information of the questionnaire question
    • Id is the unique identifier. For convenience, we make it an increment type, and save the maximum value after each increment to localStorage
    • Finally, encapsulate all fields into an object and save it in localStorage
  • Since localStorage has been used many times, it is inevitable that there will be several different keys involved, which will be stored in a separate file called constants.js for maintenance purposes
    • Question: The value is “Question”, which is used to save the temporary record of filling in the questionnaire each time
    • MaxId: the value is MaxId, which is used to save the maximum ID after the increment
    • History: The value is History, which is used to save the records submitted each time
  • Add logic to the Submit method to save the submission record
    • First, get the current maximum ID value in localStorage according to maxID. After getting the ID, increase the operation first, and then save it back to localStorage
    • {id: newId, title:QUESTION: ${newId}, user:’Yannis’, time: new Date().tolocaleString (), QUESTION: Json.stringify (result)}, (note that a JSON conversion is required to save the results of the questionnaire)
    • Retrieve the saved commit histories from localStorage based on the key History. The saved result obtained from localStorage should be an array type after JSON conversion.
    • Push the submission record object assembled above into the array body
    • After converting the array to JSON, save it back to localStorage
//constants.js
export default{
	MaxId:"MAXID".Question:"QUESTION".History:"HISTORY"
}
Copy the code
const submit = () = > {
	/ /... omit
	let maxId = localStorage.getItem(constants.MaxId);
	let newId = maxId ? ++maxId: 1;
	localStorage.setItem(constants.MaxId, newId);
	const records ={
		id: newId,
		title:` QUESTION: the first${newId}Time commit record '.user:'Yannis'.time: new Date().toLocaleString(),
		question: JSON.stringify(result)
	}
	
	const histories = localStorage.getItem(constants.History) ? JSON.parse(localStorage.getItem(constants.History)) : [];
	histories.push(records);
	localStorage.setItem(constants.History, JSON.stringify(histories)) 
	/ /... omit
}
Copy the code

Submission record Display

Now that the submission record is saved, the next step is to display the submission record as a list, using elementUI’s Table component to display the record

  • Create the HistoryList.vue component
  • Import the ElTable and ElTableColumn components of ElementUi
  • Import the REF method in VUE to define reactive variables
  • Import Constants Is used to retrieve a list of saved history records from localStorage based on key
  • Define a reactive variable data in the setup function
  • Obtain the saved historical data from localStorage based on the corresponding key value
  • JSON transforms the data and assigns it to the reactive variable data
  • Expose data to the template using a return
  • El-table and el-table-column are used in the template to display the list

The complete code for historylist. vue component is as follows:

<template>
	<el-table :data="data" stripe border style="width:100%">
		<el-table-column prop="id" label="Id" width="50" />
		<el-table-column prop="title" label="Title" />
		<el-table-column prop="user" label="User" width="150" />
		<el-table-column prop="time" label="Time" width="200" />
	</el-table>
</template>
Copy the code
import {ElTable, ElTableColumn} from 'element-plus';
import {ref} from 'vue';
import constants from './constants'
export default{
	components:{ElTable, ElTableColumn}, 
	setup(){
		const data = ref([])
		const histories = localStorage.getItem(constants.History);
		data.value = histories ? JSON.parse(histories) : [];
		return {
			data
		}
	}
}
Copy the code

Configure routing for the list page

After adding the list page, we also need to configure routing rules for the list page, modify the index.js file under the router, and add the following code in order to realize page switching:

/ /... omit
{
	path:'/list'.name:"List".component:() = >import(/*webpackChunkName: "List"*/ '.. /HistoryList.vue')}Copy the code

Modify app. vue to add submit record hyperlink

After routing is configured, we should also add an entry to the submit record list page: add a router-link in app.vue for jumping to:

<! -... Omit -- -- >
<router-link to="/list">Submit the record</router-link>
<! -... Omit -- -- >
Copy the code

Data separation

At this point, in fact, a List display function has basically been completed, but we found that the data saved in localStorage will be frequently used in different pages (such as saving data in the Home page, query data in the List page), with more and more functions and pages in the future, Therefore, data operations in localStorage will become more and more frequent. In order to facilitate future management and maintenance, we separate the relevant parts of data operations into an API file for unified management:

  • Add an index.js file to the API directory
  • In this file, define an internal function getMaxId to get or generate a self-increment ID
  • Define a saveHistory method that takes an object type parameter, Record, to hold the commit record
  • The save logic in the submit method of home. vue is split into the above two methods
  • Define a getList method to getList data from localStorage
  • Finally, external methods need to be exposed in the form of export
// api/index.js
import constants from '.. /constants'
function getMaxId(){
	let maxId = localStorage.getItem(constants.MaxId);
	let newId = maxId ? ++maxId : 1;
	localStorage.setItem(constants.MaxId, newId);
	return newId;
}

function getList(){
	const histories = localStorage.getItem(constants.History) ? JSON.parse(localStorage.getItem(constants.History)) : [];
	return histories.reverse();// By default, the most recent commit is first
}

function saveHistory(record){
	record.id = getMaxId();
	record.title = The first [` QUESTION:${record.id}【 questionnaire submission record '
	const histories = getList();
	histories.push(record);
	localStorage.setItem(constants.History, JSON.stringify(histories))
	return record.id;
}

export default {
	getList,
	saveHistory
}
Copy the code

After data is removed, the original save logic in home. vue and get logic in historylist. vue should be changed to get data directly by calling methods in API

// Home.vue
import api from './api'

const submit = () = > {
	/ /... omit
	const record ={	
		user:'Yannis'.time: new Date().toLocaleString(),
		question: JSON.stringify(result)
	}
	const newId = api.saveHistory(record)
	/ /... omit
}


// HistoryList.vue
import api from './api'
	setup(){
		const data = ref([])
		data.value = api.getList();
		return {
			data
		}
	}

Copy the code

conclusion

The list display and optimization function of the questionnaire submission records is completed. This sharing uses localStorage localStorage to save each submission record, and at the same time, the list display of submission records is instantiated with the help of elementui’s Table component. Finally, it also realized the separation of data and business and finally completed our preservation and display function. This time to share here, like small partners welcome to like comments and attention oh!