After last
Vue Family bucket +Echarts+ Baidu Map to build data visualization system
1 words before
1.1 Service Scenarios
A system that implements data monitoring. Have line chart, bar chart, map, and has the function of periodic refresh.
1.2 Service Analysis
The steps of the previous analysis were roughly as follows:
- System structures,
vue-cli
vuex
Recording Login Informationvue-router
Routing hop- Three dimensional pages, extracting common components
- Development of individual components
- Adjust styles and add UI
- Add background interface data
- To optimize the display
- test
- online
The last article covered parts 1-6. This article will cover the remaining parts 7-10.
😂 😂
The main content is the way of data processing and the overall data logic.
Hope you see the officer more suggestions and deficiencies, also hope to be able to bring inspiration to people in need.
The finished effect is not convenient to send, or use a pure front end effect picture.
2 is,
2.1 Request processing data
Vue typically uses AXIOS to interact with the background
2.1.1 installation
npm i axios
Copy the code
It can also be referenced by CDN
2.1.2 on righteousness
Create a new api.js
// api.js
import axios from 'axios'Const HTTP = axios.create ({baseURL: apiURL, // timeout: 1000 * 30, // headers: {}, // request header, which can be added'Authorization','X-Requested-With','Accept-Language','token'Etc.}) / / request intercept HTTP interceptors. Request. Use (config = > {/ / you can add their own Settings, such as modifying parameters, add, modify headersreturnConfig},error =>{// Can add error processingreturnPromise. Reject (error)}) / / intercept the HTTP response. The interceptors. Response. Use (response = > {/ / can add processing logicreturn response
},error =>{
return Promise.reject(error)
})
export default http
Copy the code
You can also add a custom global object to main.js, or reference it in a separate page
// main.js
import http from './api.js'
Vue.prototype.$http = http
Copy the code
2.1.3 use
A. get request
When processed in the page
query(){
this.$http.get('/xxx/xxx? id='+id). Then (res =>{// return console.log(res) // general contains code data},rej =>{// error console.log(rej)})}Copy the code
B. a post request
new(){
this.$http.post('/xxx/xxx',{
id : '123',}). Then (res =>{// return console.log(res) // res generally contain code data},rej =>{// error processing console.log(rej)})}Copy the code
C. Other requests
It’s often used as well
Put is used for update operations
Delete is used to delete data
It depends on the function interface mode provided by the background
D. Multiple requests
For example, when I enter the page, I want to get two line graphs, numbers, maps, bars, and tables at the same time
Typically, individual data is provided by a separate interface. So we need at least 6 interfaces.
async query() {letthat = this await axios.all([that.get1(), that.get2(), that.get3()]).then(axios.spread((res1, res2, Res3) =>{// res1 for get1 // res2 for get2 // res3 for get3}))}get1() {return this.$http.get('/xxx/xxx')}get2() {return this.$http.get('/xxx/xxx')}get3() {return this.$http.get('/xxx/xxx')}Copy the code
2.2 log in
The function is very simple, the user enters the user name, password, verification code, click login.
2.2.1 for uuid
For reasons of validity and security. During login authentication, the background verifies the UUID and the verification code obtained by the UUID.
Here are some ways to get a UUID. Source: Network.
Method one:
getUUID () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
})
},
Copy the code
Method 2:
generateUUID() {
var d = new Date().getTime()
if (window.performance && typeof window.performance.now === "function") {
d += performance.now()
}
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16)
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16)
})
return uuid
}
Copy the code
Method 3:
guid() {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4())
}
Copy the code
Method 4:
/* Specifies the length and cardinality */function uuid2(len, radix) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(' ');
var uuid = [],
i;
radix = radix || chars.length;
if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
var r;
uuid[8] = uuid[13] = uuid[18] = uuid[23] = The '-';
uuid[14] = '4';
for (i = 0; i < 36; i++) {
if(! uuid[i]) { r = 0 | Math.random() * 16; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; }}}return uuid.join(' ');
}
Copy the code
2.2.2 Password Encryption
--input
type="password"The contents of the input box can be hiddenCopy the code
I used MD5 encryption for transmission
npm i -S js-md5
Copy the code
import md5 from 'js-md5'
let enCode = md(code)
Copy the code
Then it is to call the background interface to send your user name, password, verification code to verify login.
2.2.3 Storing Login Information
As anyone who has used Vue knows, when using Vuex, you refresh the page and the data in the Store is reset.
It prevents users from being unable to obtain data after refreshing the page. Generally, data is stored in sessionStorage or localStorage at the same time
The difference between the two is not introduced here.
Sessionstorage.setitem (---- json.stringify (info) sessionStorage.setitem ())'info'.'123')
Copy the code
// store.js
store = {
state : JSON.parse(sessionStorage.getItem('info') | | {}}Copy the code
So when the page refreshes, the Store gets our data from sessionStorage
2.3 Service Page
The business page is divided into three dimensions.
The implementation of two dimensions is described here.
2.3.1 Overall logic
A separate component deals only with the presentation of the data
For example, a line graph is written in a component
I referenced it in the desired page, passing in the data for display.
- After user login authentication, the service is saved
ID
到session
From the login page to the Layer 1 page. - Once you get to level 1,
created
Add an initialization method to the. That’s what we used aboveaxios.all
- Take the data and render it into each component.
- After initialization, periodic refresh development is triggered.
- According to the timer time, trigger the function to be refreshed, as above
axios.all
And processing results. - Click on a data in level 1 to record what level 2 requires
ID2
到session
To switch to the Layer 2 page. - After entering Layer 2, the system performs initialization and then periodically refreshes the system at layer 1.
- Level 3 and the return logic are basically the same as above.
Here are some questions you might have
2.3.2 Hierarchical Page Examples
It introduces some processing of some parent and child components.
Vue <template> <div id="xxx">
<a-com ref="aRef" :args="argA"/>
<b-com ref="bRef" :args="argB"/>
</div>
</template>
<script>
import Acom from './a.vue'
import Bcom from './b.vue'
import store from './store.js'
export default {
components : {
'a-com':Acom,
'b-com':Bcom,
},
created(){// initialize method this.init()},mounted(){this.timeq()},data() {
returnStore argA: {}, argB: {}, timimg:false,
}
},
methods: {
async init() {let id1 = store.state.info.id1
await this.query(id1)
this.timimg = true
},
timeq(){// Here we define 5S refresh oncelet that = this
this.timequery = setInterval(() =>{
if(timimg){
that.querytime(store.state.info.id1)
}
},5000)
},
async query(id){
letThat = this await axios.all([that.get1(id), that.get2(id)]).then(axios.spread((res1, res2) =>{ Trigger component A's initialization method that.arga = res1.data that.$refs.aRef.init(); ArgB = res2.data that.$refs.bRef.init(); }))}, queryTime (id){// same query()}, get1(id){return this.$http.get('xxx')
},
get2(id){
return this.$http.get('xxx'}, // jump to level 2goto2(){
this.timing = false
if(this.timequery){clearInterval(this.timequery)} // replace, push, can also use name this.$router.replace('./path2')
},
}
}
</script>
Copy the code
2.3.3 Component Page Examples
// If you use the parent component to pass values to child components, define props in the child component's data for receiving // echarts initializationinitVar myChart = this; var myChart = this;$echarts.init(document.getElementById("id"),'temp')
letMychart.setoption (option = {} option = {// mychart.setoption (option,true)}}Copy the code
There’s one caveat here
Horizontal bar chart, the first one at the bottom, when we customize the title, we use it upside down.
At the same time will automatically switch the position according to the number, our table header also need to adjust the position according to the number.
2.4 test
Honestly, I haven’t really written about it…
General business changes, the logic will change frequently.
But writing test code is important.
Vue officially recommends using Karma, Mocha, chai, etc.
If you are interested, you can learn about it
This chunk is nothing less than writing business code 😅😅😅
There’s not much more to say here.
2.5 a package
npm run build
Copy the code
You can create vue.config.js in the root directory
Official document: cli.vuejs.org/zh/config/
. / / the official document: https://cli.vuejs.org/zh/config/ module exports = {baseUrl: process. The env. NODE_ENV = = ='production' ? '/' : '/',}Copy the code
Remember after 3
Thank you for your support. If insufficient, welcome to point out, mutual encouragement.
If you like it, please like it and thank you 😂
Welcome to my:
This article adoptsCreative Commons Attribution – Non-commercial Use – Same way Share 4.0 International LicenseGrant permission.
Source: github.com/xrkffgg/Too…