A, instructions,
Introduction to 1.
<body>
<div id="app">
<div>{{msg}}</div>1. Tags are used to fill data interpolation expressions</div>
<script type="text/javascript" src="js/vue.js"></script>2. Import the vue.js library file<script>
var vm = new Vue({ 3.Using vue's syntax EL:'#app'.// The mount position of the el element
data { // data model data, the value is an object
msg: 'Hello Vue' 4.Fill the tag with the data provided by vUE}})</script>
</body>
Copy the code
2. V-cloak prevents blinking during page loading
How it works: Hide content by style first, make a worthy replacement in memory, and display the final result after replacement
<style>
[v-cloak] { /* Hide the tag with a V-cloak through the property selector */
display: none;
}
</style>
<body>
<div id="app">
<div v-cloak>{{msg}}</div> <! -- Add interpolation syntax for the V-cloak property, the cloak will be removed automatically when the data is rendered.
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script>
var vm = new Vue({
el: '#app',
data {
msg: 'Hello Vue'}})</script>
</body>
Copy the code
3. V-text Fills the label with data
No flicker problem when applied to interpolation expressions. Note: This is one-way binding, the values on the data object change and the interpolation changes. Interpolating changes does not affect the value of the data object
<body>
<div id="app">
<div v-text="msg"></div> <! Insert variable name in v-text --> insert variable name in v-text
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script>
var vm = new Vue({
el: '#app',
data {
msg: 'Hello Vue'}})</script>
</body>
Copy the code
4. V-html can fill HTML fragments into tags and output them as HTML tags
5. V-pre skips compilation and displays directly
6. V-once Performs one-time interpolation. When data changes, the interpolation content is not updated
Application scenario: The displayed information does not need to be modified. Use V-once
7. V-model two-way data binding
The view changes when the data changes. When the view changes, data is restricted to < INPUT >< SELECT ><textarea> components with synchronous changesCopy the code
V-model principle (V-bind data, V-ON data processing)
<div id="app">
<input v-bind:value="msg" v-on:input="handle">
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
msg: "hello"
},
methods: {
handle: function(event){
this.msg = event.target.value;
}
}
})
</script>
Copy the code
8. V-on is used to bind events
- No parameter V-on :click abbreviation @click
<div id="app">
<div>{{num}}</div>
<div>
<button v-on:click="num++">Click on the</button> <! -- bind events to elements with v-on -->
<button @click="num++">Click on the 1</button> <! -- use @ instead of -->
<button @click="handle">Click on the 2</button> <! -- bind function name directly -->
<button @click="handle()">Click on the 3</button>
</div>
</div>
<script type="text/javascript">
var vm = new Vue({
el: "#app"
data: {
num: 0
},
methods: {
handle: function(){
console.log(this === vm) // This is the VM instance object
this.num++; }}})</script>
Copy the code
- The V-ON event function passes in arguments
<div>
<div>{{num}}</div>
<! By default, the event object is passed as the first argument to the event function.
<button v-on:click="handle">Click on the</button>
<! The event object must be passed as the last argument and the name must be $event-->
<button v-on:click="handle1(12, $event)">Click on the 1</button>
</div>
<script>
var vm = new Vue({
el: '#app'.data: {
num: 0}, the methods: {handle: function(event){
console.log (event. The target. The innerHTML)}, handle1:function(p, event){
console.log(p)
console.log(event.target.innerHTML)
this.num++
}
}
})
</script>
Copy the code
- Event modifier
<a v-on:click.stop="doThis"></a> <! Stop bubble event.stopPropagation()-->
<a v-on:click.submit.prevent="onSubmit></a> <! -- Prevent default"event.preventDefault(a)-->
v-on:click.stop.prevent <! -- Prevents bubbling and also prevents default -->
v-on:click.prevent.self <! -- Modifiers are ordered and will block all clicks -->
v-on:click.self.prevent <! Block only clicks on the element itself -->
Copy the code
- Key modifier
<input v-on:keyup.13="submit"> <! Call vm.sumit() when keyCode = 13 -->
<input v-on:keyup.enter="submit">
<input v-on:keyup.enter.space="alerMe"> <! -- Hit Enter /space to call vm.alterme ()-->
Copy the code
Common key modifier
.enter .tab .delete .esc .space .up .down .left .right
Copy the code
Customizing key modifier aliases using config.keycodes
<div id="app">
<input v-on:keydown.f5 = "prompt()">
</div>
<script>
Vue.config.keyCodes.f5 = 116;
var vm = new Vue({
el: "#app",
methods: {
prompt: function(a){
alter("I am f5"); }}})</script>
Copy the code
9. Bind the V-bind attribute
V-bind :href abbreviated to href(corresponding to js getAttribute/setAttribute)
- A binding object can give V-bind :class an object to dynamically switch classes. Note: The V-bind :class directive can coexist with the normal class feature
<ul v-bind:class="{textColor: isColor, textSize: isSize}">
<li>learning</li>
<li>Js</li>
</ul>
<div v-bind:style="{color: activeColor, fontSize: activeSize}">Object syntax</div>
<script>
var vm = newVue ({el:"#app",
data: {
isColor: true,
isSize: true,
active: "red",
active: "25px"}})</script>
Copy the code
- Binding array
<ul :class="[classA, classB]">
<li>learning</li>
</ul>
<div :style="[styleObj1, styleObj2]"></div>
<script>
var vm = new Vue({
el: "#app",
data: {
classA: 'textColor',
classB: 'textSize'
},
styleObj1: {
color: 'red'
},
styleObj2: {
fontSize: '30px'}})</script>
Copy the code
10.v-if
11.v-show
12. V-for loop object/array/plain element
Two, Vue common features
1. Basic operations of the form
Gets the values in the checkboxes, v-Model gets the values in the checkboxes, V-Model gets the values in the dropdowns and text boxes, V-ModelCopy the code
2. Form modifiers
.number
.trim
.lazy <! Change input event to change event, update only when you lose focus or press enter
Copy the code
3. Custom commands
1.Vue.directive Registers the global directive
<input type="text" v-focus> <! -- no arguments -->
<input type="text" v-color="msg">
<script>
Vue.directive('focus', {// No parameters
inserted: function(el){
el.focus()
}
})
Vue.directive('color', {
bind: function(el, binding){ el.style.backgroundColor = binding.value.color; }})var vm = new Vue({
el: '#app',
data: {
msg: {
color: 'blue'}}})</script>
Copy the code
- Register local directives in directives
<input type="text" v-focus> <! -- no arguments -->
<input type="text" v-color="msg">
<script>
var vm = new Vue({
el: '#app',
data: {
msg: {
color: 'blue'
}
}
directives: {
color: {
inserted:function(el){
el.focus()
}
},
focus: {
bind:function(el, binding){ el.style.backgroundColor = binding.value.color; }}}})Copy the code
4. Computed attributes (their responsive dependent cache)
Suitable for processing multiple variables or objects and returning a single result value. If one of the variables changes, the monitored value changes as well
<div>
<div>{{reverseString}}</div>
</div>
<script>
var vm = new Vue({
el: 'app'.data: {
num: 100
},
computed: {
reverseString: function(){
console.log('computed')
var total = 0;
for(var i=0 ; i <= this.num; i++){
total += i;
}
return total; // Be sure to return}}})</script>
Copy the code
5. Listener Watch (watch property must be data that already exists in data)
When you need to listen for changes to an object, normal Wacth methods can’t listen for changes to properties inside the object. As long as the data in data can listen for changes, the deep property is needed to listen deeply for the object
<div id="app">
<div>
<span>Name:</span>
<span>
<input type="text" v-model='firstName'>
</span>
</div>
<div>
<span>Last name:</span>
<span>
<input type="text" v-model='lastName'>
</span>
</div>
<div>{{fullName}}</div>
</div>
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data: {
firstName: 'Jim',
lastName: 'Green',
},
watch: {
firstName: function(val) {
this.fullName = val + ' ' + this.lastName;
},
lastName: function(val) {
this.fullName = this.firstName + ' '+ val; }}});</script>
Copy the code
6. The filter
Application: Double curly brace interpolation and V-bind expressions support cascading operations
<div id="app">
<div>{{msg | upper | lower}}</div>
<div :abc='msg | upper'>The test data</div>
<div> {{ message | filterA('arg1', 'arg2') }}</div> <! -- With parameter filter -->
</div>
<script type="text/javascript">
Vue.filter('lower'.function(val) { // Global filter
return val.charAt(0).toLowerCase() + val.slice(1);
});
Vue.filter('filterA'.function(n,a,b){ // n --> message a/b ---> arg1/arg2
if(n<10) {return n+a;
}else{
returnn+b; }});var vm = new Vue({
el: '#app',
data: {
msg: ' '
},
filters: { // Local filter
upper: function(val) {
return val.charAt(0).toUpperCase() + val.slice(1); }}});</script>
Copy the code
7. Lifecycle hooks
Commonly used hook functions
Hook function | instructions |
---|---|
beforeCreate | After instance initialization, data observation and event configuration are called and data and methods and the DOM structure of the page are not initialized and nothing can be done, right |
created | Called immediately after instance creation when data and methods are available but the page has not been rendered |
beforeMount | It’s called before the mount starts when you don’t have any real data on the page and it’s just a template page |
mounted | El is replaced by the newly created vm.$el, which is called after being mounted to the instance. The data is actually rendered to the page and we can use some third-party plugins in this hook function |
beforeUpdate | Called when data is updated and occurs before the virtual DOM is patched. The data on the page is still old |
updated | This hook is called after the virtual DOM is re-rendered and patched due to data changes. The data on the page has been replaced with the latest |
beforeDestroy | Called before instance destruction |
destroyed | Called after instance destruction |
9. Dynamic array responsive data
Vue. Set (a, b, c) // Let trigger view update again, data dynamic display a to change the number of data b data c changed after the dataCopy the code
Vue component
1. Global registration
Vue.com Ponent (‘ Component name ‘, {})
<div id="example">
<my-component></my-component>
</div>
<script>
Vue.component('my-component', {
template: '<div>A custom </div>'
})
new Vue({
el: '#example'
})
</script>
Copy the code
Component Considerations
The data value of the component parameter must be a function and the function must return an object the component template must be a single root element and the content of the component template can be a template string
<div>
<button-counter></button-counter>
</div>
<script>
Vue.component('button-counter', {
data: function() {return {
count: 0
}
},
template: `
<button @click="handle"Number > click {{count}} < / button > < div > test < / div > `, the methods: {handle:function(){
this.count += 2
}
}
})
</script>
Copy the code
2. Partial registration
<div id="app">< my-component></my-component> </div> <script> var Child = {// Define component template template:'
A custom component!
'
}
new Vue({
components: {
'my-component': Child
}
})
</script>
Copy the code
3. Value transfer between Vue components – Parent component passes value to child component
The way the parent component sends a value to the child component: the way the child component receives it: props receives it
<div id="app">
<div>{{pmsg}}</div>
<! -- menu-item is nested in APP, so menu-item is subcomponent -->
<! Pass a static value to the child component -->
<menu-item title='Value from parent component'></menu-item>
<! Ptitle = 'data'; ptitle = 'data'; ptitle = 'data'; Values can be numbers, objects, arrays, etc. -->
<menu-item :title='ptitle' content='hello'></menu-item>
</div>
<script type="text/javascript">
Vue.component('menu-item', {
// 3. The child component uses the props property to receive data from the parent component
props: ['title'.'content'],
data: function(a) {
return {
msg: 'Data for the child component itself'
}
},
template: '<div>{{msg + "----" + title + "-----" + content}}</div>'
});
var vm = new Vue({
el: '#app',
data: {
pmsg: 'Contents of parent component',
ptitle: 'Dynamically bound Properties'}});</script>
Copy the code
4.Vue component to Vue component – child component to parent component
Subcomponent: UseEmit () takes the custom event name as the first argument and the data to pass as the second argument
Parent component: Uses V-on to listen for events of child components
<div id="app">
<div :style='{fontSize: fontSize + "px"}'>{{pmsg}}</div>
<! The parent component can monitor the event of the child component using the v-ON function. If the first parameter in the $emit function is magnanime-text, the handle should be the corresponding event handler.
<menu-item :parr='parr' @enlarge-text='handle($event)'></menu-item>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
/* The child passes a value to the parent - with arguments */
Vue.component('menu-item', {
props: ['parr'].template: ` < div > < ul > < li: key = 'index' v - for = '(item, index) in parr' > {{item}} < / li > < / ul > # # # 1, the child components with $emit () triggering event # # # the first parameter in the name of the event for custom < button@click ='$emit("enlarge-text", 5) > enlarge the font size in the parent component < button@click ='$emit("enlarge-text", '
});
var vm = new Vue({
el: '#app'.data: {
pmsg: 'Contents of parent component'.parr: ['apple'.'orange'.'banana'].fontSize: 10
},
methods: {
handle: function(val){
// Increase the font size
this.fontSize += val; }}});</script>
Copy the code
5. Value transfer between Vue components — Value transfer between sibling components
Event center passes data provides event center var hub = new Vue() passes data, triggering the hub through an event.$emit(method name, data passed) Receive data, passmounted() {} hook, triggers the hub.$on() Method name destruction event, via hub.$offUnable to pass data after method name is destroyedCopy the code
<div id="app">
<div>The parent component</div>
<div>
<button @click='handle'>Destruction of the event</button>
</div>
<test-tom></test-tom>
<test-jerry></test-jerry>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
/* Data transfer between sibling components */
//1. Provide the event center
var hub = new Vue();
Vue.component('test-tom', {
data: function(a){
return {
num: 0
}
},
template: `
<div>
<div>TOM:{{num}}</div>
<div>
<button @click='handle'</button> </div> </div> methods: {handle:function(a){
$emit(method name, data passed) emits an event from the hub.$emit(method name, data passed) emits an event from the other component
hub.$emit('jerry-event'.2);
}
},
mounted: function(a) {
// Locate the hub.$on(mounted(){} hook)
hub.$on('tom-event', (val) => {
this.num += val; }); }}); Vue.component('test-jerry', {
data: function(a){
return {
num: 0
}
},
template: `
<div>
<div>JERRY:{{num}}</div>
<div>
<button @click='handle'</button> </div> </div> methods: {handle:function(a){
$emit(method name, data passed) emits an event from the hub.$emit(method name, data passed) emits an event from the other component
hub.$emit('tom-event'.1);
}
},
mounted: function(a) {
// Locate the hub.$on() {// locate the hub.$on() {// locate the hub
hub.$on('jerry-event', (val) => {
this.num += val; }); }});var vm = new Vue({
el: '#app',
data: {
},
methods: {
handle: function(a){
//4, the destruction event was destroyed by the hub.$off() method name
hub.$off('tom-event');
hub.$off('jerry-event'); }}});</script>
Copy the code
6. Component slot
Anonymous slot
<div id="app">
<! If no value is passed, the default value in slot will be used.
<alert-box>Have a bug in</alert-box>
<alert-box>There is a warning</alert-box>
<alert-box></alert-box>
</div>
<script type="text/javascript">/* Component slot: parent component passes content to child component */ Vue.component('alert-box', {template: '<div>
<strong>ERROR:</strong># When the component is rendered, this<slot>The element will be replaced with "nested content in component tags". Slots can contain any template code, including HTML<slot>The default content</slot>
</div>`});</script>
</body>
</html>
Copy the code
A named slot
Bind elements using the “name” attribute in
<div id="app">
<base-layout>
<! The value of this slot must match the name value of the following slot components. If no match is found, the slot will be placed in an anonymous slot.
<p slot='header'>Header information</p>
<p>Main Content 1</p>
<p>Main Content 2</p>
<p slot='footer'>Bottom Information</p>
</base-layout>
<base-layout>
<! Template temporary package tag will not render to the page -->
<template slot='header'>
<p>Title Message 1</p>
<p>Title Message 2</p>
</template>
<p>Main Content 1</p>
<p>Main Content 2</p>
<template slot='footer'>
<p>Bottom Information Information 1</p>
<p>Bottom Information Information 2</p>
</template>
</base-layout>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">Vue.component('base-layout', {template: '<div>
<header>### 1<slot>The "name" attribute binding element specifies the name of the current slot<slot name='header'></slot>
</header>
<main>
<slot></slot>
</main>
<footer>The rendering order of the named slots depends entirely on the template, not on the order of the elements in the parent component<slot name='footer'></slot>
</footer>
</div>`});</script>
</body>
</html>
Copy the code
Scope slot
- Parent component to child component processing
- You can either reuse the slots of the child components or make the slot contents inconsistent
<div id="app">
<fruit-list :list='list'>
<template slot-scope='slotProps'>
<strong v-if='slotProps.info.id==3' class="current">
{{slotProps.info.name}}
</strong>
<span v-else>{{slotProps.info.name}}</span>
</template>
</fruit-list>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
Vue.component('fruit-list', {
props: ['list'],
template: `
<div>
<li :key='item.id' v-for='item in list'>In the child component template,<slot>The element has a function (MSG =" XXX ") for props to pass data to the component. The ### slot can provide a default content, and if the parent component does not provide content for the slot, the default content will be displayed. ### If the parent component provides content for the slot, the default content is replaced<slot :info='item'>{{item.name}}</slot>
</li>
</div>`}); var vm = new Vue({ el: '#app', data: { list: [{ id: 1, name: 'apple' },{ id: 2, name: 'orange' },{ id: 3, name: 'banana' }] } });</script>
</body>
</html>
Copy the code
4. The way of interface invocation
- Native ajax
- Jquery-based Ajax
- fetch
- axios
1. The asynchronous
- JS common asynchronous calls
- Timing of any
- ajax
- Event functions
2. promise
promise
var p = new Promise(function(resolve, reject){ // This is used to implement asynchronous tasks
setTimeout(function(){
var flag = false;
if(flag) { // Normal condition
resolve('hello');
}else{ // Abnormal condition
reject('Wrong'); }},100);
});
p.then(function(data){
console.log(data)
},function(info){
console.log(info)
});
Copy the code
Promise to send the Ajax
function queryData(url) {
var p = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState ! =4) return;
if(xhr.readyState == 4 && xhr.status == 200) { // Handle normal situations
resolve(xhr.responseText);
}else{ // Handle exceptions
reject('Server error'); }}; xhr.open('get', url);
xhr.send(null);
});
return p;
}
// Send multiple Ajax requests in order
queryData('http://localhost:3000/data')
.then(function(data){
console.log(data)
return queryData('http://localhost:3000/data1');
})
.then(function(data){
console.log(data);
return queryData('http://localhost:3000/data2');
})
.then(function(data){
console.log(data)
});
Copy the code
Promise the commonly used API
function foo() {
return new Promise(function(resolve, reject){
setTimeout(function(){
// resolve(123);
reject('error');
}, 100); })} foo() is equivalent to foo().then()function(data){ .then(function(data){
console.log(data) console.log(data)
},function(data){ }).catch(function(data){
console.log(data) console.log(data)
}) })
.finally(function(){ .finally(function(){
console.log('finished') console.log('finished')}); });Copy the code
function queryData(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState ! =4) return;
if(xhr.readyState == 4 && xhr.status == 200) { // Handle normal situations
resolve(xhr.responseText);
}else{ // Handle exceptions
reject('Server error'); }}; xhr.open('get', url);
xhr.send(null);
});
}
var p1 = queryData('http://localhost:3000/a1');
var p2 = queryData('http://localhost:3000/a2');
var p3 = queryData('http://localhost:3000/a3');
// Promise.all([p1,p2,p3]).then(function(result){
// console.log(result)
// })
Promise.race([p1,p2,p3]).then(function(result){
console.log(result)
})
Copy the code
3.Fetch
fetch('http://localhost:3000/fdata').then(functionThe (data){// text() method, which is part of fetchAPI, returns a Promise instance object that gets the data returned in the backgroundreturn data.text();
}).then(function(data){
console.log(data);
})
Copy the code
4. The Fetch API calls the interface to pass parameters
GET parameter pass – traditional URL
fetch('http://localhost:3000/books? id=123', {
method: 'get'
})
.then(function(data){
return data.text();
}).then(function(data){
console.log(data)
});
Copy the code
GET Passes the restful URL
fetch('http://localhost:3000/books/456', {
method: 'get'
})
.then(function(data){
return data.text();
}).then(function(data){
console.log(data)
});
Copy the code
DELETE Request mode parameter passing
fetch('http://localhost:3000/books/789', {
method: 'delete'
})
.then(function(data){
return data.text();
}).then(function(data){
console.log(data)
});
Copy the code
POST Requests the parameter to be transmitted
fetch('http://localhost:3000/books', {
method: 'post',
body: 'uname=lisi&pwd=123',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function(data){
return data.text();
}).then(function(data){
console.log(data)
});
Copy the code
fetch('http://localhost:3000/books', {
method: 'post',
body: JSON.stringify({
uname: 'Joe'.pwd: '456'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data){
return data.text();
}).then(function(data){
console.log(data)
});
Copy the code
PUT Requests to transfer the parameter
fetch('http://localhost:3000/books/123', {
method: 'put',
body: JSON.stringify({
uname: 'Joe'.pwd: '789'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data){
return data.text();
}).then(function(data){
console.log(data)
});
Copy the code
5. Data format of the Fetch response result
fetch('http://localhost:3000/json').then(function(data){
// return data.json();
return data.text();
}).then(function(data){
// console.log(data.uname)
// console.log(typeof data)
var obj = JSON.parse(data);
console.log(obj.uname,obj.age,obj.gender)
})
Copy the code
6. Basic usage of AXIos (Axios is a library)
axios.get('http://localhost:3000/adata').then(function// Console. log(ret. Data) console.log(ret)})Copy the code
7. Axios requests parameter passing
Axios GET Request parameter transmission
axios.get('http://localhost:3000/axios? id=123').then(function(ret){
// Ret is an object. All objects are stored in ret's data property
console.log(ret.data)
})
axios.get('http://localhost:3000/axios/123').then(function(ret){
console.log(ret.data)
})
axios.get('http://localhost:3000/axios', {
params: {
id: 789
}
}).then(function(ret){
console.log(ret.data)
})
Copy the code
Axios delete The parameter is passed
axios.delete('http://localhost:3000/axios', {
params: {
id: 111
}
}).then(function(ret){
console.log(ret.data)
})
Copy the code
Axios POST Requests parameters to be passed
axios.post('http://localhost:3000/axios', { // Default JSON data
uname: 'lisi'.pwd: 123
}).then(function(ret){
console.log(ret.data)
})
var params = new URLSearchParams(); // Form data
params.append('uname'.'zhangsan');
params.append('pwd'.'111');
axios.post('http://localhost:3000/axios', params).then(function(ret){
console.log(ret.data)
})
Copy the code
Axios put Indicates that the parameter is passed
axios.put('http://localhost:3000/axios/123', {
uname: 'lisi'.pwd: 123
}).then(function(ret){
console.log(ret.data)
})
Copy the code
8. Result of axios response
axios.get('http://localhost:3000/axios-json').then(function(ret){
console.log(ret.data.uname)
})
Copy the code
9. Configure axiOS globally
// configure the request's baseURL address axios.defaults.baseURL ='http://localhost:3000/'; // configure the request headers axios.defaults.headers['mytoken'] = 'hello';
axios.get('axios-json').then(function(ret){
console.log(ret.data.uname)
})
Copy the code
10. Axios interceptors
Request interceptor
axios.interceptors.request.use(function(config) {
console.log(config.url)
config.headers.mytoken = 'nihao';
return config;
}, function(err){
console.log(err)
})
Copy the code
Response interceptor
axios.interceptors.response.use(function(res) {
// console.log(res)
var data = res.data;
return data;
}, function(err){
console.log(err)
})
Copy the code
11. Basic usage of async functions
Async /await processing asynchronous operations: Async functions return a Promise instance object and await can be followed directly by a Promise instance object
Axios and async
axios.defaults.baseURL = 'http:localhost:3000';
axios.get('adata').then(function(ret){
console.log(ret.data)
})
axios.defaults.baseURL = 'http:localhost:3000';
async function queryData() {
var ret = await axios.get('adata');
// console.log(ret.data)
return ret.data;
}
Copy the code
Async and promise
async function queryData() {
var ret = await new Promise(function(resolve, reject){
setTimeout(function(){
resolve('nihao')
},1000);
})
// console.log(ret.data)
return ret;
}
queryData().then(function(data){
console.log(data)
})
Copy the code
12. Async /await processing of multiple asynchronous tasks
axios.defaults.baseURL = 'http://localhost:3000';
async function queryData() {
var info = await axios.get('async1');
var ret = await axios.get('async2? info=' + info.data);
return ret.data;
}
queryData().then(function(data){
console.log(data)
})
Copy the code
Vue-Router
1. Routing: It is essentially a correspondence relationship
Routes are divided into front-end routes and back-end routes: 1. Back-end routes are implemented by the server and distribute resources. 2. Front-end routing is implemented by changing hash values (anchor chains)
2. Front-end routing
Front-end routing is implemented based on changes in the hash value (for example, clicking a menu or button in a page to change the HASH value of a URL, and controlling component switching based on changes in the hash value). The core implementation relies on an event, that is, an event that listens for changes in the hash value
window.onhashchange = function(){//location.hash retrieves the latest hashhashValue of the location. The hash}Copy the code
3.Vue Router
Vue Router features:
H5 historical mode or Hash mode Nested routines supported routing parameters Supported programmatic routing Named routing Supported navigation guard Supported transition animation supported lazy loading supported scrolling of routes
4. Use vue-router
- A. Import the JS file
<script src="Lib/vue_2. 5.22. Js." "></script>
<script src="Lib/vue - router_3. 0.2 js." "></script>
Copy the code
- B. Add route link: the tag provided in the route is rendered as a tag by default. The to attribute is rendered as an href attribute by default, and the value of the to attribute is rendered as a hash address starting with #
<router-link to="/user">User</router-link>
<router-link to="/login">Login</router-link>
Copy the code
- C. Add route padding bits (Route placeholders)
<router-view></router-view>
Copy the code
- D. Define routing components
var User = { template:"<div>This is User</div>" }
var Login = { template:"<div>This is Login</div>" }
Copy the code
- E. Configure routing rules and create routing instances
Var myRouter = new VueRouter({//routes is an array of routes:[// Each route rule is an object. The object contains at least two attributes: path and ComponenthashAddress, component indicates the routing rule corresponding to the component object {path:"/user",component:User},
{path:"/login",component:Login}
]
})
Copy the code
- F. Mount routes to the Vue instance
new Vue({
el:"#app"Router :myRouter})Copy the code
5. Route redirection
Var myRouter = new VueRouter({//routes = new routes: [//path = / redirect = new VueRouter({//routes = new routes:]) {//routes = new routes: [//path = / redirect = new VueRouter({//routes = new routes)}"/",redirect:"/user"},
{ path: "/user", component: User },
{ path: "/login", component: Login }
]
})
Copy the code
6, nested routines by, the implementation of dynamic routing
The concept of nested routines
<body>
<div id="app"><! -- Area controlled by vm instance -->
<router-link to="/user">User</router-link>
<router-link to="/register">Register</router-link>
<router-view></router-view> <! -- Route placeholder -->
</div>
<script>
const User = {
template: '<h1>The User component</h1>'
}
const Register = {
template: `<div>
<h1>Register the component</h1>
<hr/>
<! -- Child routing links -->
<router-link to="/register/tab1">tab1</router-link>
<router-link to="/register/tab2">tab2</router-link>
<! -- Placeholder for child routing -->
<router-view />
<div>`
}
const Tab1 = {
template: '<h3>Tab1 subcomponents</h3>'
}
const Tab2 = {
template: '<h3>Tab2 subcomponents</h3>} const router = new VueRouter({routes: [// all routing rules {path: '/', redirect: '/user'}, {path: '/user', Component: user}, {path: '/register', Component: register, children: [// children array represents child routing rules {path: '/register/tab1', component: Tab1 }, { path: '/register/tab2', component: Tab2}]}]}) const vm = new Vue({// create vm instance el: '#app', // specify control area data: {}, // mount router instance object // router: router router })</script>
</body>
</html>
Copy the code
Dynamic route matching 1 Run the $route.params.id command to obtain the data of path passing parameters
var User = { template:<div> user: {{$route.params.id}}</div>"} var route = new VueRouter({//routes = routes) {path:"/user/:id", component: User },
]
})
Copy the code
Dynamic routing match 2 receives parameters through props
var User = {
props:["id"],
template:User: {{id}}} var myRouter = new VueRouter({//routes is an array of routes: [// pass the parameter through /: parameter name // if the props is set totrue, route.params will be set to the component property {path:"/user/:id", component: User,props:true]})},Copy the code
Dynamic routing match 3 Set props to object, and then pass the object’s data directly to the component for use
var User = {
props:["username"."pwd"],
template:User: {{username}}-- {{PWD}}} var myRouter = new VueRouter({//routes = new routes: [// props = object) {//routes = new VueRouter({//routes = new routes: [// props = object)"/user/:id", component: User,props:{username:"jack".pwd: 123}},]})Copy the code
4. If you want to get the values of the passed parameters as well as the data of the passed objects, then props should be set to function.
var User = {
props:["username"."pwd"."id"],
template:
User: {{id}} -> {{username}}-- {{PWD}}
} var route = new VueRouter({//routes) [// Pass the parameter as a parameter name // If props is set to function, then get the route object as the first parameter of the function and get the passed parameter as the params attribute of the route object // {path:"/user/:id", component: User,props:(route)=>{
return {username:"jack".pwd:123,id:route.params.id}
}
},
]
})
Copy the code
Named routes and programmatic navigation
Named Route: Alias the route
Var myRouter = new VueRouter({//routes = routes: [//routes: [//route: [//route: [//route: [//route: [//route: [//route: [//route: [//route: [//route]])"/user/:id", component: User, name:"user"},]}) // After you add an alias, you can jump to <router-link to="/user">User</router-link>
<router-link :to="{ name:'user' , params: {id:123} }">User</router-link> // You can also programmatically navigate myrouter.push ({name:'user' , params: {id:123} } )
Copy the code
Programmatic navigation: navigation by clicking links Programmatic navigation: call JS API methods to achieve navigation
this.$router.push("Hash address");
this.$router.push("/login");
this.$router.push({ name:'user' , params: {id:123} });
this.$router.push({ path:"/login" });
this.$router.push({ path:"/login",query:{username:"jack"}}); this.$router.go( n ); //n is a number, see history.go this.$router.go( -1 );
Copy the code