Chapter I getting to know VUE
1. Common instructions in Vue
-
v-bind: for the attribute bound by the instruction, you can write js statements in the attribute
v-bind: abbreviation:
-
v-on: this instruction is used to bind events, which will execute the methods defined in the methods object. Listen for events and add an event listener
v-on: abbreviation@ tips: when the event code is relatively simple, it can be written directly in the tag. Example:
<button @click="test = !test">Button</button>
When the event code is complex, it is best to write it to the method and then call it.
-
v-model this instruction encapsulates v-bind: and v-on:. This instruction can be used to realize two-way binding of data.
2.vue responsive principle
-
Knowledge paves the way.
-
Several common ways to add properties to object s in js
(1) Object name. Properties
object.property
(2) Object name ['attribute']
object['property']
(3)Object.defineProperty() defines a property
This method can add more settings to object properties, such as whether they can be deleted, modified, and enumerated. This method can restrict objects in more detail
Object.defineProperty(object,'property',{ value:'value', //Indicates that the attribute can be deleted. It cannot be deleted by default configurable:true,//Can be deleted writable:true,//Rewritable get(){ //This function is called when the property is accessed }, set(param){ //This function is called when the value of the property is modified //This method receives a parameter (param) -- the new value of the attribute } }) //Delete a property on an object delete object.property
-
-
Response principle
-
Manipulate the original object with a proxy object.
-
The original object is operated, and the data cannot be listened. Listen for data through proxy objects.
//Original object let obj = { prop:'value' } //Proxy object let _obj = {}; //The proxy object is used to monitor the changes of data and pass the changes to the original data Object.defineProperty(_obj,'prop',{ get(){ //Access the original object through the proxy object return obj.prop; }, set(param){ //Modify the original object through the proxy object obj.prop = param; //When the data changes, call the rendering function to re render the page. renderDOM(); } });
-
-
3. Conditional rendering
-
v-if
The v-if instruction is used for conditional rendering, and the expression returns true for rendering; If the expression returns false, the corresponding element will not be generated.
-
v-show
The v-show instruction displays hidden elements through the style display. Expression true, display; Expression false, hidden.
-
v-if v-else-if v-else
v-if, v-else-if and v-else can be used together without fault in the middle.
-
How to select V-IF & v-show?
If you only need to judge once to determine whether to show or hide, use v-if.
If you need to switch between show and hide repeatedly, use v-show.
v-if is used to judge whether to render. If you render repeatedly, it will cause a waste of resources.
v-show is just switching styles.
4. List rendering
-
v-for
The v-for instruction is used to traverse the array.
Generally, the key attribute needs to be bound, and the key attribute is a unique value. It is not recommended to bind index
<!-- item Each item of the array index Array subscript --> <div v-for="(item,index) in array" :key="unique-id"> {{item}} </div>
5.Tips
-
v-if cannot be used with v-for.
-
Usually, we wrap another layer of elements in the outermost layer of the list to control display and hiding. The problem with doing so is that the outermost elements are often meaningless. At this time, we can wrap it through Vue's built-in component template, which will not be displayed during rendering.
Example:
<template v-if="true"> <div v-for="(item,index) in array" :key="unique-id"> {{item}} </div> </template>
-
Chapter II life cycle of VUE
1. Life cycle
(1) Knowledge foreshadowing
-
HOOK function. The HOOK function captures the event at the system level when it is triggered, and then performs some operations.
A program used to process system messages. Is to give you the opportunity to do some processing at a certain stage.
-
(1) Is a function that is called by the system when a system message is triggered
(2) Not triggered by the user
-
The name of the hook function is determined. It is called automatically when the system message is triggered.
(2)vue life cycle and its hook function
-
new Vue() create instance
-
Init events & lifecycle
-
beforeCreate()
(1) Before data initialization. This stage is acting as a proxy for the data in data. (at this time, you can only operate the prototype proto)
-
-
Init injections & reactivity
-
created()
(1) Data initialization completed. At this stage, the data proxy has been completed, and the data can be operated at this time. (for example, send an ajax request to get the required data)
-
-
Has 'el' option? Is there an 'El' option?
NO
when vm.$mount(el) is called, continue after the specified container is mounted, otherwise wait indefinitely.
YES
Continue jump to next step
-
Has 'template' option? Do you have a template?
YES
Compile template into render function
NO
Compile el's outerHTML as template compiles the container into a template and puts it into the rendering function (outerHTML contains innerHTML and its tag itself)
Analysis: the rendering function generates a virtual DOM (pseudo DOM) in memory
-
beforeMount()
(1) The virtual DOM has not been converted to a real DOM before the page is mounted.
-
-
Create vm.$el and replace 'el' with it
-
mounted() *****
(1) Page mount is complete (the real DOM replaces the virtual Dom and inserts the page.)
At this point, you can manipulate the DOM.
Analysis: the virtual DOM in memory has not been destroyed.
-
-
Mounted
when data changes
-
beforeUpdate()
(1) After the data is updated, before the page is remounted.
Virtual DOM re render and patch virtual DOM re render and update.
Analysis: the new virtual DOM is compared with the "old virtual DOM" in memory, and the page update is finally completed. Model = = > View update is completed
-
updated()
(1) After the data is updated, the page is remounted.
The new template rendering is complete,
when vm.$destroy() is called
The $destroy() method is used to destroy the current instance. After destruction, the current instance object cannot continue to operate the page.
Note: the ability to render pages is no longer available, and the data and methods on the instance object still exist.
Analysis: the pseudo DOM in memory is destroyed at this time. Because there is no comparison object, all pages cannot be re rendered and updated.
-
beforeDestroy()
(1) Before the instance is destroyed, some initial and final work is generally done at this stage, such as closing the timer, clearing the data, unsubscribing messages, unbinding custom events, etc
-
-
Teardown monitors, child components and event listeners
-
destroy()
Instance destruction completed.
-
2. Life cycle diagram
Chapter III VUE Foundation
1. Binding style
-
class
Bedding
<style> .color{ color:red; } .back{ background-color:blue; } .d-f{ display:flex; } </style>
new Vue({ el:'#app', data(){ return { controlBack:true, controlColor:false, controlDF:true, /**obj written in one of two**/ obj:{ back:true, color:false, 'd-f':true, }, /***************/ bgcolor:'back', fontcolor:'color', /***************/ bg:'red', fc:'blue' } } })
-
Writing method I
: class specifies an object whose property name is style name. The property value returns a boolean value
<div :class="{back:controlBack,color:controlColor}"> HELLO </div> <!--Or. The object is written in data Medium, (see bedding), bound to class upper--> <div :class="obj"> HELLO </div>
Or use the calculated property to return the calculated property of the object (according to the official documents, this method is more commonly used)
computed:{ obj(){ return { //You can write many conditions back:this.controlBack /**&& Condition etc**/, color:this.controlColor, 'd-f':this.controlDF, } } }
<div :class="obj"> HELLO </div>
-
Writing method 2
: class specifies an array. When each item of the array is defined in data, its value is the specified style name.
<div :class="[bgcolor,fontcolor]"> HELLO </div>
-
Writing method III
: class simple expression method.
<div :class="controlBack ? 'back' : '' "> HELLO </div> <!--Binding multiple expressions, you can specify an array containing multiple expressions --> <div :class="[controlBack ? 'back' : '' , controlColor ? 'color' : '']"> HELLO </div>
-
-
Tips: when used in a component.
Vue.component('dl-tagname'/**Component tag name**/,{ template:` <div class="box"> <div>Example</div> </div> ` })
When using the class attribute on a custom component, these styles will be added to the root element of the component, and the existing classes on the root element will not be overwritten.
<dl-tagname class="back color"></dl-tagname> <!--HTML Will be rendered as:--> <div class="box back color"> <div>Example</div> </div> <!--With data binding class Also.--> <dl-tagname :class="{back:controlBack,color:controlColor}"></dl-tagname> <!--HTML Will be rendered as:--> <div class="box back "> <div>Example</div> </div>
-
style
-
Bind inline style
<div :style="{backgroundColor:bg,color:fc}"> HELLO </div> <div :style="{'background-color':bg}"> HELLO </div>
-
etc...
-
2. Calculated attribute
-
Elegant evolution. (?)
-
(1) When the expression in the template is too complex, it will make the template too heavy and difficult to maintain.
{{z=x+y}}
-
(2) Return the result by defining a method.
{{calc()}}
methods:{ calc(){ return this.z=this.x+this.y; } }
-
(3) Calculation attribute: calculation attributes define methods, which are used as attributes in the container.
Note: when defining calculation properties, do not have the same name as the method in the methods option.
-
Calculate attribute cache VS method
Calculated properties are cached based on their responsive dependencies (official documents). Responsive dependency means that new results will be returned only when the dependent data changes.
As long as the attribute (variable) value (dependent data) in the calculated attribute has not changed, multiple accesses will immediately return the previous calculation results (i.e. cached results). When the dependent data changes, it will be re evaluated.
Method, on the other hand, executes the function repeatedly every time it is called. (use this method when caching is not required)
{{calc}}<input type="text" v-model="calc">
Generally, the calculation attribute is only responsible for returning the result without modifying the content, so it is mostly defined in short form.
computed:{ //Short form: /* calc(){ //In short form, the default is the get method. When modifying the return value in the page, an error will be reported, indicating that there is no setter. return this.z=this.x+this.y; } */ //Complete form: calc:{ get(){ //When called, the get method will execute once first (that is, calculate once and return the results, which are stored in the cache. When repeated access, if the dependent data does not change, the cached results will be returned immediately). //When the value of the attribute (variable) used in get (that is, the dependent data) changes, the get method is executed once return this.z=this.x+this.y; }, set(value){ //When the * * return value * * in get changes in the page, return the new value to value for other operations this.y = value-this.x; } } }
-
-
3. Listener watch
-
The difference from the calculated attribute: the calculated attribute is only responsible for the result, while the listener can do more. (for example, when the data changes, re request the background to obtain the latest data)
-
-
Use watch when the data changes and some operations need to be performed.
watch:{ //Listen to who, in whose name //The listening property contains two parameters, the new value and the old value. x(newValue,oldValue){ console.log(newValue,oldValue) }, y(){ } }
-
Deep listening
data:{ return { params:{ a:'a', b:'b', c:{ d:'d', }, } } } watch:{ //If you need to deeply listen to a property, you need to define the listener in a complete form params:{ //Turn on deep listening deep:true, //Turn on immediate listening immediate:true, //The handler method listens for data changes. handler(newValue,oldValue){ //The reference data type does not change the object, but the properties of the object have changed (oldValue is meaningless at this time) } } }
-
4. filters
-
Define filters. (when the global filter and local filter have the same name, the local filter is adopted.)
Local filters: local filters are defined in the options of an instance or component.
//... filters:{ //... filterA(value){ //... } } //...
Global filters: Global filters are defined before Vue instances.
##All instances will have this filter. Vue.filter('filterA',function(value){ //... }); new Vue({ //... }); new Vue({ //... });
-
The methods defined in the filter can only be used in interpolation expressions and v-bind: expressions.
Indicated by | pipe symbol. Pass the value to the left of the pipe character as a parameter to the method to the right of the pipe character and return a new result. The filter can be used in series, and the results of the previous filter will continue to be transmitted to the next filter for further filtering.
{{PI | PI5 | PI2}}<input :value="PI | PI5">
data:{ return { PI:3.1415926, } }, filters:{ PI5(value){ return value.toFixed(5); }, PI2(value){ return value.toFixed(2); } }
5. v-cloak optimization template display problem
-
Solve the problem that the page template will be displayed before the page is mounted.
Just add a v-cloak attribute to the container, and then define the style of the attribute selector in the style as none.
Note: when vue mounts the real DOM into the container, the v-cloak attribute is removed
<style> /* attribute selectors */ [v-cloak]:{ display:none; /*You can also use visibility:hidden*/ } </style> <div id="app" v-cloak> ... </div>
6. v-model form input binding
-
Basic usage
data:{ return { txt:'txt', boo:true, arr:[], pick:'', op:'1', ops:[], id:1337 } }
-
text
<input v-model="txt"/>
-
Multiline text
It cannot be written in the label with interpolation statement, but can only be written in the attribute with v-model
<textarea cols="30" rows="5" v-model="txt"></textarea>
-
check box
Single check box, bound boolean
<input type="checkbox" v-model="boo">
Multiple check boxes bound to the same array
<input type="checkbox" v-model="arr"> <input type="checkbox" v-model="arr"> <input type="checkbox" v-model="arr">
-
Radio
A group of radio boxes that bind the same data.
<input type="radio" value="1" v-model="pick"> <input type="radio" value="2" v-model="pick">
-
Drop down box
For radio selection, the value in option is bound
<select v-model="op"> <!--When option Not set value When, value The default is the text value--> <option value="1">op1</option> <option value="2">op2</option> <option value="3">op3</option> </select>
When multiple selections are made, an array is bound,
<!--multiple Attribute is multiple selection--> <select multiple v-model="ops"> <!--When option Not set value When, value The default is the text value--> <option value="1">op1</option> <option value="2">op2</option> <option value="3">op3</option> </select>
-
-
Value binding
-
Modifier
-
.lazy
Update the data after the text box loses the cursor.
<input type="text" v-model.lazy="id"> <!--coordination change Use similar to onblur,Update data trigger after cursor loss change Bound events--> <input type="text" v-model.lazy="id" @change="">
-
.number
The entered numeric text (String) is converted to Number type.
<input type="text" v-model.number="id">
-
.trim
Remove spaces at both ends of the entered text.
<input type="text" v-model.trim="id">
-
Modifiers can be concatenated, for example:
<input type="text" v-model.trim.number.lazy="id">
-
-
Using v-model in components
It is omitted here and is involved in subsequent components.
Chapter V event handling
1. Listening events
-
Simple operation, you can put the processing code into the template
new Vue({ //... data(){ return { id:1337, name:'example', } } });
{{id}} {{name}} <button @click="id=1338;name='for example'">modify</button>
-
Complex operations, defining event methods and calling
When the method call does not pass parameters, the event object (e) is passed in as the first parameter by default,
//... methods:{ changeExample(/*e*/){ this.id = 1338; this.name = 'for example'; } } //...
<!--...--> <button @click="changeExample">modify</button>
-
Complex operation, passing parameters through event method
If the parameter is passed, the default event object will not be passed. If you still want to use the event object, you need to pass the event object $event when calling
//... methods:{ //... changeExampleWithParams(/*e,*/id,name){ this.id = id; this.name = name; } }
<!--...--> <button @click="changeExampleWithParams(/*$event,*/1339,'for for example')">modify</button>
-
Keyboard event modifier
Trigger the binding event after pressing the specified key (v-on: | @)
-
. enter
-
. tab tab tab
-
. delete (capture delete and backspace keys)
-
. esc exit
-
. space spaces
-
. up
-
. down
-
. left left
-
. right right right
<!--...--> <!--Key codes can also be used, not recommended--> <!--<intput type="text" :value="name" @keyup.13="changeName">--> <intput type="text" :value="name" @keyup.enter="changeName">
//... methods:{ //... changeName(e){ // Gets the current element value this.name = e.target.value } } //...
-
-
-
. stop ----- > event. Stoppropagation() prevents bubbling
-
. prevent ----- > event. Preventdefault() blocks default events
-
.capture
-
. self child elements no longer inherit events
-
. once is triggered only once
-
. passive scrolling triggered in real time
<!--...--> <a href="https://Google. Com "@click.prevent =" changeid "> block default events</a> <div style="width:200px;height:200px;background-color:red" @click="redOne"> <div style="width:100px;height:100px;background-color:green" @click.stop="greenOne"> Prevent event bubbling </div> </div>
//... methods:{ //... changeId(/*e*/){ //e.preventDefault(); / / block the default method this.id = 1340; }, redOne(){ alert('I am the red one'); }, greenOne(/*e*/){ //e.stopPropagation(); / / component event bubbling alert('I am the green one'); } } //..
-
2. Responsive principle - non responsive case
(Vue does not support IE8 and earlier browsers)
-
Object
Adding or removing a property does not trigger a response
Set the response type through Vue.set(object,propertyName,item) or this.$set(object,propertyName,item)
//... data(){ return { // obj:{ id:1337, name:'example', } } }, methods:{ // changeObj(){ this.obj = { id:1339, name:'for example', } }, // addProperty(){ //this.obj.prop = 'A Property'; / / adding object properties directly cannot achieve dynamic response //Add a response to the newly added property of the object Vue.set(this.obj,'prop','A Property'); //perhaps this.$set(this.obj,'prop','A Property'); }, deleteProperty(){ //Deletes the property of the specified object and removes the response of the property Vue.delete(this.obj,'name'); //perhaps this.$delete(this.obj,'name'); } } //...
{{obj}} <!-- --> <button @click="obj.id = 1338">modify</button> <!-- --> <button @click="changeObj">modify obj object</button> <!-- --> <button @click="addProperty">to obj Add attribute</button> <!-- --> <button @click="deleteProperty">delete obj Properties of</button>
-
Array
Modifying elements according to the index does not trigger a response if the array length is modified
Set the response formula through Vue.set(arr,index,item)
Array response methods: push, pop, unshift, shift, reverse, splice, sort
//... data(){ return { arr:[233,2333,23333], } }, methods:{ pushOne(){ //Responsive //this.arr.push(233333); //Non responsive //1. When using index to directly set array items this.arr[3] = 233333; }, popOne(){ //Responsive //this.arr.pop(); //Non responsive this.arr.length = 2; } } //...
{{arr}} <button @click="pushOne">Add an element</button> <button @click="popOne">Delete last item</button>
Chapter 7 custom components
1. Custom components
//... //Register global components Vue.component('dl-box',{ template:`<div> <div>This is a custom component<div> </div>`, }) new Vue({ //... data(){ return { example:'example' } }, components:{ //Register local components //Define a DL box component //Other options except el option can be written in the component. To avoid data pollution, the data option in the component must be a method whose return value is an object 'dl-box':{ //The template option sets the content of the component. Note: the template in the template can only contain one root label template:`<div> <div>This is a custom component{{example}}<div> </div>`, data(){ return { } }, //props option, which is used to receive data passed externally to the component //Props short form is a string array, which defines the received attribute name. The data received by props can be used directly in the template //Custom properties props:['propertyName'] //... }, } //... })
<dl-box propertyName="example"></dl-box>
2. Transfer parameters of components
-
Parameter transfer, modification and return
//... Vue.component('dl-example',{ template:`<div> <h1>{{backupData}}</h1> <button @click="backupData='for for example'"></button> </div>`, //The complete form of props, which passes an object, the attribute of the object, and the corresponding attribute name. //In particular, the data in props is read-only and cannot be modified props:{ propertyName:{ //Specify the attribute type type:String,// //The property cannot be empty //required:true, //The default value of the property //default:'example' } }, data(){ return { //Back up the data transmitted by props in the data of the component and modify the data in the data backupData:this.propertyName } }, //Monitor data changes watch(){ //When bacupkData changes backupData(){ //Trigger a custom event through $emit. The event name is xxx. The custom event calls the xxfn method this.$emit('xxx'/*Custom event*/,this.backupData/*Event object*/) } } }) //... new Vue({ //... data(){ example:'for example' }, methods:{ xxxFn(eventObject/*That is, the backupData value in the component*/){ //Re assignment completes the return of parameters this.example = eventObject } } })
<dl-example :propertyName="example" @xxx="xxxFn"></dl-example> {{example}}
Data transfer path in the instance: component custom attribute > > > > > component backup attribute value > > > > listen for backup data > > > > > return as a custom event object > > > > > > re assignment of the original data is equal to data return.
3. Component slot
-
In the template of the component, use the slot tag to define the slot
Vue.component('dl-example',{ template:`<div> <slot></slot> </div>`, //... })
All html content between custom component tags will be displayed at the position of the slot tag in the component
<dl-example> <img src="" alt=""> </dl-example>
4. Execution sequence of component life cycle and vue instance life cycle
-
After the Vue instance data is prepared, the component data will be prepared
-
From the beginning of rendering to the completion of rendering, the Vue instance must render the components first.
-
Lifecycle of Vue instances
-
beforeCreate
-
created
-
beforeMount
-
Component lifecycle
-
-
mounted
-
5.$parent ,$children
-
The $parent attribute returns the parent component instance of the current component
You can repeat. $parent, such as this.$parent.$parent
-
The $children property returns all child component instances of the current component. The return value is an array. The specified component can be obtained according to the subscript of the array
Note: it is not reliable to obtain the specified component information according to the subscript, because the location may change.
6.$refs ,$root
-
$refs attribute
Add a ref attribute on the component tag to define the unique identity of the component through different attribute values
<dl-example ref="exampleRef"></dl-example>
//$refs is used to get all components with ref attribute, and the return value is an object. Object stores all components with ref attribute
this.$refs.exampleRef
-
$root attribute
$root returns the root component
7. Third party UI component library
-
Element UI
-
iView
8. Go deep into v-model
-
v-bind: bind value attribute v-on: bind input event to realize bidirectional binding
<input type="text" :value="name" @input="name=$event.target.value">
-
The v-model instruction is the syntax of v-bind: and v-on:
When only one data needs to be passed to the component and the two-way binding of data is realized, v-model can be used,
<input type="text" v-model="name">
-
Custom components implement two-way binding
-
v-bind: v-on: $emit returned data
-
The bound property name is changed to value, and the bound event name is changed to input. At this time, v-model shorthand can be used
-
9 sync modifier
-
When multiple copies of data are passed to components and two-way binding of multiple copies of data is required, v-model is not competent,
-
The. sync modifier is now available
Note that if the event name is defined in the form of update: propertyName
this.$emit('update:propertyName',param)
When calling a component, you can omit the calling steps of the event, and just follow the. sync modifier after the attribute
<input type="text" :propertyName.sync="name" :propertyName2.sync="age">
10. Named slot
-
The slot tag is used to define the slot inside the component. You can define the name of the slot through the name attribute. This slot is called a named slot
If no slot name is defined, it is called default by default
Vue.component('dl-example',{ template:`<div> <slot name="header"></slot> <div> <slot name="content"></slot> </div> <slot name="footer"></slot> </div>`, //... })
v-slot: abbreviation#
<template #header> </template> <template #content> </template> <template #footer> </template>
11. Scope slot
-
The scope slot must be a named slot.
The so-called scope slot actually binds its own attributes to the slot
Vue.component('dl-example',{ template:`<div> <div v-for="(item,index) in list" :key="item.id"> {{item}} <slot name="header" :abc="item" :def="index" :ghi="list"></slot> </div> </div>`, //... })
Use the v-slot instruction of the template tag to specify a specific slot
If there is data returned from the slot, you can specify an object through the assignment statement. The object name is user-defined, usually named scoped. Scoped means scope
<template #header="scoped"> {{scoped}} <button @click="scoped.abc.name='hhhhhh'">modify</button> <button @click="scoped.ghi.splice(scoped.def,1)">delete</button> </template>
12.mixin mixing
-
Global blending
Vue.mixin({}) method is used to globally mix members into Vue, such as data, methods, life cycle function, etc
After mixing in, all Vue instances will have these members
For example, mixed encapsulated request methods
-
Local blending (generally, local blending is rarely used, which is of little significance, unless it is imported from the outside)
mixin:[{}]