As for the Mock data, the library mock. js is used here. As for the usage, the official website also explains in detail, so I will briefly introduce it here.
The list of data
Our first project in SRC/components/HelloWorld vue deleted, the SRC/router/index js to make the following changes:
import Vue from 'vue'
import Router from 'vue-router'
import Index from '@/views/vacation/'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Index',
component: Index
}
]
})Copy the code
Then, create index.vue in SRC /views/vacation/ :
<template>
<div>list view</div>
</template>Copy the code
According to the effect
In mobile mode, the display is as follows:
Simulated data
From the project root, use the command line NPM I -d mockjs;
New SRC/mock/list. Js:
import { mock, Random } from "mockjs";
export default mock({
'list|0-50': [
{
'approveId': '@id',
'applier': {
'userId': '@guid',
'userName': '@cname',
'sectionId': '@id',
'sectionName': '@ctitle',
}
...
}
]
})Copy the code
- Here,
'@id'
(called “placeholders”) isRandom.id()
Short form of “; - Here,
'@id'
(called “placeholders”) must be enclosed in quotation marks; - Here,
'@id' + 111
Will be will be'@id'
As a string (returns'@id111'
), does not equalRandom.id() + 111
;
New SRC/mock/index. Js:
Mock. Js intercepts the request address:
import { mock, Random } from "mockjs";
import List from "./list";
mock('\/','get',()=> List);Copy the code
- In this case, use
Mock.mock( rurl? , rtype? , function( options ) )
Intercepting a routing request/
Path, return simulatedList
List. -
Rurl: Intercepts the path rule, which can be a string ‘/’ or a regular expression /\//.
- If the request
/? id="1"
.mock
The intercept path of can be written asMock.mock(/\/? id=\"\d\"/,'get',()=>List)
; - If different request parameters are required, return the corresponding parameters
id
You need to intercept your own dataurl
String to judge;
- If the request
-
rtype
Interception request type,get
orpost
; -
Function (options) : callback function, intercepting successful processing logic;
-
optioins = {url, type, body}
; -
url
Is the request address; -
type
Is the request type; -
body
For the data passed in at request time (only atpost
Useful when requested);
-
State management
Here, we use vuex for state management, and AXIos requests data: NPM i-s vuex axios;
New SRC/store/index. Js:
import Vue from 'vue'; import Vuex from 'vuex'; import axios from 'axios'; Vue.use(Vuex); const $setApplications = 'SETAPPLICATIONS'; export default new Vuex.Store({ state: { applications: null, }, mutations: { [$setApplications]: (state, list) => state.applications = list, }, actions: { requestApplications({ commit, state }) { axios.get('/') .then(({data:{list}}) => { commit($setApplications, list); }) .catch(() => { console.log(arguments); }}}})Copy the code
- Here,
state
Save the public state of the entire project,mutations
For synchronous data processing,actions
Handle asynchronous requests. -
mutations
Is the only modificationstate
The entrance,actions
If you want to modifystate
It needs to be called internallymutations
; -
In the project application, use this. Codestore.mit (‘SETAPPLICATIONS’,null) to change the value of state.
- To pass multiple values, the second argument is an object (no more than one argument is accepted, at most two arguments are accepted).
-
In the project, an asynchronous request is invoked via this.$store.dispatch(‘requestApplications’).
- If you need to pass a parameter, pass a second parameter (no more than one parameter is accepted, at most two parameters are accepted);
The request data
So far, through the above steps, we have built simulated data and state management independently, but have not yet combined them.
SRC /main.js add import ‘./mock’, import store from ‘./store’ and modify:
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})Copy the code
Over?
Not yet, we need to get the data: in the SRC/views/vacation/index. The vue add:
<script>
export default {
beforeCreate(){
this.$store.dispatch('requestApplications');
}
}
</script>Copy the code
Trigger the request.
Request the results
The Mock. Js usage
If you want to see how mock. js is used, it is recommended to see the “Documentation” page of the official website rather than the “examples” page.
Mock. Js returns all data in object format, if you want to fetch other formats (such as arrays…) I need to find my own way.
The rules
Format:
Mock. Mock ({// initialize the object, which is also the output object; })Copy the code
Syntax specification:
Each attribute in the data template consists of three parts: attribute name, generation rule, and attribute value:
/ / the name attribute name/value rule / / / generate rules attribute value ‘name |’ rule: the value
Attribute names and generate rules with vertical lines between | separated (don’t take space around, otherwise, your property name may contain Spaces).
The generation rule is optional.
There are seven formats for generating rules:
‘name|min-max’: value
‘name|count’: value
‘name|min-max.dmin-dmax’: value
‘name|min-max.dcount’: value
‘name|count.dmin-dmax’: value
‘name|count.dcount’: value
‘name|+step’: value
The meaning of the generation rule depends on the type of the attribute value.
Attribute values can contain @ placeholders.
The property value also specifies the initial value and type of the final value.
validation
If you want to verify that your written simulation data is correct, you can open the console on the “Examples” page and run it directly.
Mock.mock({
'list|1-10':[
Random.id(),
]
})Copy the code
The test results
vue-devtools
The installation address
Use to remind
-
$vm0
Points to a component instance that must have the console’sVue
Tab page, click on a component to obtain, otherwise, report$vm0 undefined
. - Click on which component,
$vm0
Which component to point to to get a property on that component.
Chapter reviews
- Know how to simulate the data, next I will secretly simulate the list of data, you do not forget.
- How to use
Mock.js
How about intercepting the request, how do you get the data at the time of the request? - How to use
axios
What about request data? It’s the same asmutations
What’s the difference?
thinking
- Lazy goods a, select a third party list library, how in
Vue
What about in the project?
Relevant official documents
MockJS uses documents
MockJS Sample (console test available)
Vuex website
One day
Vue usage – the router