vue.js
Vue(pronounced like View) is a set of progressive frameworks for building user interfaces. Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom up. Vue’s core library focuses only on the view layer, making it easy to get started and integrate with third-party libraries or existing projects. On the other hand, when combined with modern toolchains and various supporting libraries, Vue is perfectly capable of providing drivers for complex, single-page applications.
Reference documents: the Denver nuggets: night evening I https://juejin.cn/post/6844903912340717575 the nuggets: bbuh https://juejin.cn/post/6844903623554498567Copy the code
First, VUE foundation
1. Basic architecture of vue.js
<div id="app"> </div> <! <script SRC =".. /js/vue.js"></script> <script> var app = new Vue({ el:"#app", data:{ } }) </script>Copy the code
2. Some instructions of Vue
Directives are special properties prefixed with v- and written on the HTML label. The responsibility of a directive is to apply some behavior to the DOM when the value of its expression changes.
Common commands include the following:
- Data binding directives: Display data as the contents of elements.
v-text
v-html
v-model
- Attribute directives: Set data as attributes of elements. Example class, SRC, etc.
v-bind
- Conditional instruction:
v-if v-elseif v-else
v-show
- Cycle instruction
v-for
1. v-text
V-text is equivalent to the interpolation syntax {{}}. Only text can be parsed, and the parsed text is used as the content of the tag.
<p v-text="ad"></p> == <p>{{ad}}</p>
data:{ad:"abcdefg"}
Copy the code
2. v-html
This is similar to V-text. But it can parse HTML tags.
<p v-html="ac"> </p> data: {ac:"<h1> This is a title </h1>"}Copy the code
3. v-model
Implement two-way data binding (V-model is a syntax-sugar for @input + :value)
There are requirements for labels. It cannot be attached to the SPAN tag: because Span cannot take input from the user, the user cannot directly modify the content of the Span.
It is more suitable to be added to form elements. Such as input. Users can change the content of the input.
P > {{AD}} < / p > < input v - model = "AD" type = "text" / > / / data: {AD: "initial value, can also be empty"}Copy the code
4. v-bind
< tag ** V-bind :** Attribute name = “Data configuration item set attribute name” >
Action: When the value of an expression changes, the resultant effects are applied to the DOM in a responsive manner
There are two attributes that are individually set to special use because they are used so much:
style Class
<! <a v-bind:href="url">... </a> <! <a :href="url">... </a>Copy the code
5. v-if
The V-if directive is used to conditionally render a piece of content. This content will only be rendered if the expression of the directive returns true.
You can also add an “else block” with v-else:
<p v-if="false">1111111</p> <p v-else>22222222</p> <! -- V-else must be immediately followed by an element with v-if or v-else-if, otherwise it will not be recognized. You can use the V-else -if directive to form a nested conditional loop --> <p v-if="true">1111111</p> <! The true or false after the v-if directive can also be replaced with an expression, but enclosed in quotation marks -->Copy the code
Because v-if is an instruction, it must be added to an element. But what if you want to switch between multiple elements? You can treat a
element as an invisible wrap element and use v-if on it. The final render will not contain the
element.
6. v-show
The option for displaying elements by conditions is the V-show directive. The usage is roughly the same as v-if
** The difference is that elements with v-show are always rendered and remain in the DOM. V-show simply toggles the element’s CSS attribute display. V-show =false equals display= None
<p v-show="true">1111111</p>
Copy the code
7. v-if VS v-show
V-if is “true” conditional rendering because it ensures that event listeners and subcomponents within the conditional block are properly destroyed and rebuilt during the switch.
V-if is also lazy: if the condition is false during initial rendering, nothing is done — the conditional block is not rendered until the condition is true for the first time.
V-show, by contrast, is much simpler — elements are always rendered regardless of initial conditions and simply switch based on CSS.
In general, V-if has a higher switching overhead, while V-show has a higher initial rendering overhead. Therefore, v-show is good if you need to switch very frequently; It is better to use V-if if conditions rarely change at run time.
8. v-for
< tag v-for= “(value,key,index) in obj” ></ tag >
<p v-for="value in 10">{{value}}</p> // from one to tenCopy the code
-
Obj is the data defined in the data configuration item.
-
It produces multiple labels
-
Value,index, and key are just parameter names that can be changed and omitted in order as needed
-
The data available for circulation are:
- The third parameter is useless when the array loops through the array.
- object
- In the integer to integer loop, the index starts at 0
V-for can be used to loop through an array loop object integer
Vue 2.5 +, use V-for, need to add key key must be unique
The key is used to distinguish elements, and is now usually bound with a key
Do not use index as the key. Index may cause some problems when data changes. If there is a unique identifier, use a unique identifier.
9. v-slot
After Vue 2.6.0, a new V-slot syntax was adopted to replace slot and slot-scope
Second,vue
The configuration of the item
Method 1.methods
New Vue() sets configuration items such as data for data. One of these configuration items is Methods, which are optional and may or may not be written.
What it does is you can write some logical code and call it like a function.
Call method one: Outside the vue instance, access it via app.f1(), app.f2().
Call method 2: Inside the VUE instance, call directly. Usually used in {{}} or v-bind
To call another method from one method, add this
<div id="app"> {{f1()}} // Inside the vue instance, call directly. </div> <script> var app = new Vue({ el: "#app", data: {}, / / to use commas here the methods: {f1 () {}, / / will use commas between each function f2 () {}}}) < / script >Copy the code
2. Calculate propertiescomputed
The computed property, computed, is also a configuration item for vUE instances. Declaratively describes a value that depends on another value.
Usage: Generally, the initial data (data items) are processed and returned with new data.
Call: A computed property is essentially a function, but it is called like a normal data item without the addition of ().
<script> Var vm = new Vue({el: "#app", data: {}, methods: {}, computed attribute name: function () {return value; }}}) </script>Copy the code
The difference between calculating a property and a method:
- Calculation properties are cached, functions are not!
- The function is sensitive
- The difference used to calculate properties is that they are essentially methods, but instead of adding (), methods add ().
3. The filterfilters
Filters are used to format data. Like EL, Data, Methods, and CopuTED, it is a configuration item of a VUE instance.
Data formats: {{| filter}}
Multiple filters used together:
Format: {{data item 1 | | filters filter 2}}
Filters transform data before being instructed to process it and display it into a view without having to modify the original data in scope, allowing the same data to be presented in different forms in different parts of the application.
<div id="app"> <p>{{f|fixss(1)}}</p> </div> <! <script SRC =".. /js/vue.js"></script> <script> var app = new vue ({el: "#app", data: {f: 3.14154,}, methods: {}, computed: {}, filters: {fixss(d, n) {return d.tofixed (n)}}}) </script>Copy the code
When writing the filter function, pay attention to the corresponding relationship of parameters in the transfer process:
- The first parameter (required) is the data item that you must filter.
- The arguments following the second (optional) argument are the arguments you write in ()
If there are two or more parameters, you do not need to enter the first parameter and enter the second and subsequent parameters
Special features of filters:
- It is defined with at least one argument, which is called without arguments: the default argument to the first argument is the item you want to filter.
- It ** must have a return value **, which is consistent with evaluating properties.
3. Event V-ON
1. Introduction
- Vue handles events through the V-ON instruction
You can use the V-ON directive to listen for DOM events and run some JavaScript code when triggered.
Format: < Event source tag V-ON: Event type = “event handler function” >
<! <a v-on:click="doSomething"> </a> <! < a@click ="doSomething">... </a>Copy the code
Example:
<div id="example-1"> <button v-on:click="counter += 1">Add 1</button> <p>The button above has been clicked {{ counter }} times.</p> </div> <script> var example1 = new Vue({ el: '#example-1', data: { counter: 0 } }) </script>Copy the code
However, much of the event handling logic is more complex, so it is not feasible to write JavaScript code directly into v-ON instructions. So V-ON can also receive a method name that needs to be called.
2. Writing position
- If the code is simple: write directly on the line
- If the code is complex: Add a new method to methods and call it in V-ON
3. Event type
- Mouse events, click, dblclick, mouseover, mouseout, mouseenter, mouseleave, mousedown, Mousemove, mouseup
- Keydown, keyPress, keyUp,
- UI events, Scroll, resize, Load, unload
- Focus events, focus, blur
- Form event, change, submit
Calling event.preventDefault() or event.stopPropagation() in the event handler is a very common requirement. While this could easily be done in a method, it’s better if the method has pure data logic instead of dealing with DOM event details.
To solve this problem, vue.js provides event modifiers for V-Ons.
-
.stop
-
.prevent
-
.capture
-
.self
-
.once
-
.passive
<! Continue to spread, stop the click event - - > < v - on a: click. Stop = "doThis" > < / a > <! <form V-on :submit. Prevent ="onSubmit"></form> <! - the modifier can series - > < v - on a: click. Stop. Prevent = "doThat" > < / a > <! <form V-on :submit. Prevent ></form> <! -- Use event capture mode when adding event listeners --> <! <div V-on :click.capture="doThis"> <div V-on :click.capture="doThis"> </div> <! Trigger handler only if event.target is the current element itself --> <! <div v-on:click.self="doThat">... </div>Copy the code
When using modifiers, order is important; The corresponding code is generated in the same order. Therefore, using V-on :click.prevent. Self blocks all clicks, whereas V-on :click.self. Prevent only blocks clicks on the element itself.
Key modifier
When listening for keyboard events, we often need to check for detailed keystrokes. Vue allows v-ONS to add key modifiers when listening for keyboard events:
<! Call 'vm.submit()' only if 'key' is' Enter '--> <input V-on :keyup. Enter ="submit"> <! KeyboardEvent. Key you can directly convert any valid keyname exposed by KeyboardEvent to kebab-case as a modifier. --> <input v-on:keyup.page-down="onPageDown">Copy the code
In the example above, the handler is only called when $Event. key equals PageDown.
There are the following key modifiers:
.enter .tab .delete .esc .space .up .down .left
.right .ctrl .alt .shift .meta
1. @input
Note: In VUE, listening for input input events uses the V-ON directive. V-on: input = “func” or @input = “func”
Example:
<input value="text" @input="onInput"> <script> //... methods: {onInput(e) {console.log(e) // The argument e is an InputEvent object, $emit("input"); // This.$emit("input"); // This. e.target.value); } } </script>Copy the code
In the example, bind an input event to the input field and set onInput in the method, where the argument e is
4. Form input binding
You can use the V-model directive to create two-way data binding on forms ,
Bidirectional data binding: Bidirectional only on form elements.
v-model
All form elements will be ignoredvalue
,checked
,selected
The initial value of the feature and always the Vue instance data as the data source. You should use JavaScript in the componentdata
Option to declare the initial value.
The V-Model internally uses different attributes for different input elements and throws different events:
- Text and Textarea elements are used
value
Properties andinput
Events; - Checkbox and radio use
checked
Properties andchange
Events; - The select field will
value
As prop and willchange
As an event.
1. The single box
- Multiple input:radio names must be the same. This is a single choice
- The V-models of multiple input: radios must be the same.
- The initial value you set must correspond to the value in input:radio.
<! <div id="app"> <input type="radio" name="sex" V-model ="add" value=" male "> male <input type="radio" name="sex" V - model = "add" value = "female" > women < h1 > {{add}} < / h1 > < / div > <! <script SRC =".. /js/vue.js"></script> <script> var app = new Vue({ el: "#app", data: { add:"" }, methods: {}, computed: {}, filters: {} }) </script>Copy the code
2. Check box
There are two common uses:
(1) Only one check box. Used to say “agree” or not. Represents a radio option, usually represented by a Boolean value.
<input type="checkbox" v-model="agree">
Copy the code
(2) Multiple check boxes. Select one or several options from multiple options. Represents multiple choices, usually represented by arrays. For example, for statistical interests, you can use v-Models to bind data
<! -- agree button - > < div id = "app" > < input type = "checkbox" v - model = "add" > agree < h1 > {{f1 ()}} < / h1 > < / div > < script SRC = ".. /js/vue.js"></script> <script> var app = new Vue({ el: "#app", data: { add:"true" }, methods: { f1(){return this.add?" Agree ":" not "}}, computed: {}, filters: {}}) < / script >Copy the code
<! <div id="app"> <template v-for="ass in allfav"> <input V-model ="info.favoriate" type="checkbox" :value="ass.value">{{ass.name}} </template> <hr/> <p>{{info}}</p> </div> <script src=".. /js/vue.js"></script> <script> var app = new vue ({el: "#app", data: {allfav: [{name: "read ",value: "book"}, {name: Value: "sing", "song"}, {name: "game", value: "game"}, {name: "sleep", value: "sleep"}], info: {favoriate: [" book "]}}, the methods: {}, computed: {}, filters: {} }) </script>Copy the code
No V-Model bidirectional binding is used
<div id="app">
<input type="text" :value="add" @input="abcd">
<h2>Input: {{add}}</h2>
</div>
<!-- 引入vue.js文件 -->
<script src="./vue.js"></script>
<script>
var vm = new Vue({
data: {
add: "aa",
abb: ' '
},
methods: {
abcd(e) {
this.add = e.target.value
}
}
}).$mount('#app')
</script>
Copy the code
3. Drop – down list
Make a drop-down list using the SELECT and option directives
<! - a simple drop-down list -- > < div id = "app" > < select v - model = "info. Study" name = "" id =" "> < option value =" - please select - > "- please select - < option > < option v-for="i in eduOption" v-model:value="i">{{i}}</option> </select> <hr/> <p>{{info}}</p> </div> <! <script SRC =".. /js/vue.js"></script> <script> var app = new Vue({ el: "#app", data: { info: {study: "please select -"}, eduOption: [" key ", "a", "2", "three"],}, the methods: {}, computed: {}, filters: {}}) < / script >Copy the code
4. Modifiers
.lazy
By default, v-Model synchronizes the value of the input field with the data each time the input event is triggered (except when the input method combines text as described above). You can change to synchronization using the change event by adding the lazy modifier:
<! <input v-model. Lazy =" MSG ">Copy the code
.number
If you want to automatically convert user input values to numeric types, you can add the number modifier to the V-Model:
<input v-model.number="age" type="number">
Copy the code
This is often useful because even when type=”number”, the value of the HTML input element always returns a string. If the value cannot be resolved by parseFloat(), the original value is returned.
.trim
If you want to automatically filter whitespace entered by the user, you can add the trim modifier to the V-model:
<input v-model.trim="msg">
Copy the code
Five, components,
In VUE, everything is a component.
Components are our own extended “HTML elements” that encapsulate reusable code.
At a higher level, components are custom elements to which the vue.js compiler adds special functionality.
Components are one of the most powerful features of vue.js.
1. The root component
In let VM = new Vue({}) we get a VM that is an object (or instance) of a Vue, which can also be understood as a component, except that it is the root component of everything else.
By way of distinction, we’re going to define “child components.”
2. The child component
There are two ways to use components:
- Global components
- Local components
1. Global components
Define a global component through Vue’s static method component()
Template: is the content of the HTML tag to be displayed by the component, which replaces the HTML tag you defined
Global components: All VUE instances are available
<div id="app"> <! <my-header></my-header> <! -> </div> <! <script SRC =".. /js/vue.js"></script> <script> <! - global components - > Vue.com ponent (" myHeader ", {/ / myHeader for component name, can change the template: "< div > < div >" this is a global components / / fixed format, Quotation marks inside can change}) let app = new Vue ({el: "# app," data: {}, the methods: {}, conputed: {}, filters: {},}) < / script >Copy the code
2. Local components
Local components can only be used in the registered instance, not in other instances.
1. Simple parts
<div id="app"> <! - using registered name for reference here child components - > < myhead > < / myhead > < son > < / son > < / div > <! <script SRC =".. /js/vue.js"></script> <script> // You can define components here let myhead={template:"<div> this is a root component </div>"} let app = new vue ({el: "#app", data: {}, components: {myhead:myhead, // Template :"<div> is another root component </div>"}}}) </script>Copy the code
2. Slightly complex local components
<div id="app"> <son></son> </div> <! When the child component is too complex, it can be written outside, >< template id="son"> <div> <button></button> </div> </template> </body> <script SRC =".. /js/vue.js"></script> <script> let son = { template: }} let app = new Vue({el: "#app", data: "#app", data: "#app", data: {}, methods: {}, components: {son}}) </script>Copy the code
3. Some details
1. The definition name
If there are multiple words, the first letter of each word is uppercase.
For example, MyHeader EleUser
2. The registered name
There’s no name requirement. Generally consistent with component names: Use the shorthand rules for object property names in ES6 to abbreviate:
For example: MyHeader: MyHeader, which can be abbreviated as MyHead,
3. Use the name
When using a component, its name must be all lowercase!!
Say the first two names of your component:
- Define the name
- Registered name
For components, you must use the Kebab nomenclature: uppercase to lowercase, preceded by an underscore “-“
Conclusion: Suggested writing method
Definition name | Registered name | Use the name |
---|---|---|
Big hump nomenclature | Be consistent with the definition name. Es6 for short | Kebab nomenclature |
4. Subcomponent format
<script> let son = {//son is the component name, Template :"", data:function(){return{// data}} return{// your data item}}} </script>Copy the code
Component interaction
1. The father the son
- In the parent component, you normally define your own data
- Data is bound to child components using property binding in the parent component’s template.
- Define the props property in the child component. Used to receive data passed by the parent component.
- Properties defined in props are used to retrieve data from the parent component, so they can be used as items defined in data.
For each item, three properties can be added to modify it.
Props:{
Data item name :{
Type: type. Specifies what type of data must be passed from the parent component. Its value is: Object, Array, a String, Number, Boolean is the constructor. Don’t write it as a string.
Default :// Default value. This value is used when the parent component does not transmit data.
Required: true/false. Does it have to be passed on.
}
}
<div id="app"> <! <son: sonValue ="num"></son> </div> <template id="son"> <div> <! - to use the data in child elements - > < h1 > {{sonvalue}} < / h1 > < h1 > {{sonnum}} < / h1 > < / div > < / template > < script SRC = ".. /js/vue.js"></script> <script> let son = { template: "#son", data(){ return{ sonnum: }}, props:{sonValue :{// Type :Number, props:{sonvalue:{// }} let app = new Vue({el: "#app", data: {num:10}, components: {son}}) </script>Copy the code
Note: You cannot modify the data passed by the parent directly in the child component
Solution: In the child component, after receiving the data from the parent component, you can use this data to initialize the data defined in the child component, and then you can delete the data defined in the child component.
2. The father
Adds an event listener on a child of a parent component
Format: < child component @ Child component returns event name =” method to be executed by parent component “>
Note: The child component returns event name in lower case
And define “methods to be executed by the parent” in the parent component
Emit this event at some point in the child component via this.$emit
<body> <div id="app"> <h1> Parent component </h1> <! Add an event listener to the child component --> <! -- submitMsg is an event --> <! The child component emits an event that triggers the addmsg function --> <! - addmsg is a function of the parent component - > < son @ submitmsg = "addmsg" > < / son > < h4 > {{a}} < / h4 > < / div > < template id = "son" > < div > < h3 > subcomponents < / h3 > </button> </div> </template> </body> <script SRC ="./vue.js"></script> <script> let Son = { // Subcomponent template: "#son", data() {return {}}, methods: {this.$emit("submitmsg",66666)}} let vm = new Vue({// parent component el: "#app", data: {a:0}, components: {Son}, methods: {addmsg(info) {// console.log(info) info == 666 this.a = info}}) </script>Copy the code
3. The father sun
Father to son to son (father to son), can only be passed on one level, not across levels
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
<! - binding events, data transmission, with the father and the son, among them, because of a, b is direct transfer of literal, so do not need to bind the data in the data - >
<my-button :msg="content" a="1" b="2"> </my-button>
</div>
</body>
<script>
/ / the parent component
let vm = new Vue({
el: "#app".data: {content:"点我"
},
// Son component
components: {
"MyButton": {//mounted
mounted(){
// this.$attrs If the child receives data that is not needed, the data is saved in $attrs
console.log(this.$attrs)
},
// Again, bind events and transfer data
template:'
subcomponent
'.// Grand-level components
components:{
'my': {props: ['a'.'b'].template:' Sun component {{a}}----{{b}}'}}}}})</script>
</html>
Copy the code
Results:
Sub-component Grandson component 1----2Copy the code
4. Children trigger methods in their parents
For example click click on the event change
1. The way a
@click.native
1. When binding events to the VUE component, native must be added; otherwise, it will be considered that the events that are customized from the Item component are monitored
$emit(“click”.fn); $emit(“click”.fn);
Think of Click as a serious click event and let a child component fire that event. Change @click=”change” to @click.native=”change” when calling child components
One disadvantage of this approach is that the click event is triggered on the line where the SON component is clicked
<div id="app">
<h1>This is the parent component</h1>
<son @click.native="change"> </son>
</div>
<script>
let vm = new Vue({
el: "#app".data: {
content: "Little"
},
methods: {
change() {
alert(1)}},components: {
son: {
template: '',}}})</script>
Copy the code
2. 2
@click="$listeners.click()"
All v-ON-bound events are placed on $Listeners
Can be set when defining child components
Template: ` < div > < button @ click = $listeners. Click "()" > me < / button > < / div > `Copy the code
Note that all v-ON-bound events are stored on $Listeners:
<my-button @click="change" @mouseup="change"></my-button> // Set the child template: '<div><button $listeners ></ button></div>Copy the code
Example:
<div id="app">
<h1>This is the parent component</h1>
<son @click="change"> </son>
</div>
<script>
let vm = new Vue({
el: "#app".data: {
content: "Little"
},
methods: {
change() {
alert(1)}},components: {
son: {
template: ` < h2 > < button @ click = "$listeners. Click ()" > this is child components < / button > < / h2 > `,}}})</script>
Copy the code
Three (3) way
@click="$emit('click')"
This is to use $emit to trigger events in the parent
Example:
<div id="app">
<h1>This is the parent component</h1>
<son @click="change"> </son>
</div>
<script>
let vm = new Vue({
el: "#app".data: {
content: "Little"
},
methods: {
change() {
alert(1)}},components: {
son: {
template: ` < h2 > < button @ click = "$emit (' click ')" > this is child components < / button > < / h2 > `,}}})</script>
Copy the code
4. Trigger two events simultaneously
All events using the V-ON binding are placed on $Listeners
<div id="app">
<h1>This is the parent component</h1>
<son @click="change" @mouseup="change"> </son>
</div>
<script>Let vm = new Vue({el: "#app", data: {content: ""}, methods: {change() {alert(1)}}, components: {son: { template: `<h2>
<button @click="$listeners.click()">This is child component 1</button>// Trigger once<button @click="$emit('click')">This is child component 2</button>// Trigger once<button v-on="$listeners">This is child component 3</button>// Trigger twice</h2>`,}}})</script>
Copy the code
5.provide
inject
The provide option should be an object or a function that returns an object. This object contains properties that can be injected into its descendants.
2. Inject is equivalent to the props of the enhanced subcomponent
Both can be in parent and child, grandchild, great-grandchild… Component data interaction, that is, not limited to parent-child component data interaction of prop, as long as the declaration of provide in the upper layer, then the lower layer can access the data provided by inject, no matter how deep
Where, provide is declared in the parent component at the same level as data in the form of provide:{key: value},
When receiving descendant components, its inject is the same as data, and the format is Inject :[key]
Provide and Inject mainly provide use cases for high-level plug-in/component libraries. Direct use in application code is not recommended.
This pair of options needs to be used together to allow an ancestor component to inject a dependency into all of its descendants, regardless of how deep the component hierarchy is, and remain in effect as long as the upstream and downstream relationship is established. If you’re familiar with React, this is very similar to the context features of React.
Seven, route guard
Create => Mount => Update => Destroy
Figure 1. The reference
Example 2.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The life cycle</title>
<script src="./vue.js"></script>
</head>
<body>
<div id="app">
{{ flag }}
</div>
</body>
<script>
let vm = new Vue({
el: "#app".data: {
flag: "Life cycle"
},
// Used to initialize the life cycle and bind its own events
beforeCreate() {
console.log("Before creation:");
console.log(this.$el); //undefined
console.log(this.$data); //undefined
},
// Initiate Ajax. Ajax is asynchronous and does not interrupt
created() {
console.log("Created complete:");
console.log(this.$el); //undefined
console.log(this.$data); //{__ob__: Observer}
},
// You can also send ajax requests before calling the render function for the first time
beforeMount() {
console.log("Before mounting:");
console.log(this.$el); //<div id="app"> {{ flag }}</div>
console.log(this.$data); //{__ob__: Observer}
},
// Use ajax to get the real DOM after the page is rendered
mounted() {
console.log("Mount complete:");
console.log(this.$el); //
Lifecycle
console.log(this.$data); //{__ob__: Observer}
},
// Do not use it
beforeUpdate() {
console.log('Before update render');
let flag = this.$refs.app.innerHTML;
console.log('flag:' + flag);
},
// Does, but failure to manipulate data with the updata hook may result in an infinite loop
updated() {
console.log('Update completed');
let flag = this.$refs.app.innerHTML;
console.log('flag:' + flag);
},
// Some cleaning can be done before destruction
beforeDestory(){
console.log("Before destruction:");
},
/ / destroyed
destoryed(){
console.log("Destruction completed:"); }});</script>
</html>
Copy the code
3. Explain
BeforeCreate (): The instance is created in memory, but the data and methods properties have not been initialized.
Create (): The instance has been created in memory, data and method have been initialized, and the template has not yet been compiled.
BeforeMount (): The template is compiled but not mounted to the page.
Mounted () : displays a compiled template in a specified container.
BeforeUpdate (): The function is executed before the status update, when the status value in data is the latest, but the data displayed on the interface is old because DOM nodes have not been re-rendered.
Updated (): At this point, the status values in data and the data displayed on the screen have been updated and the screen has been re-rendered.
BeforeDestroy (): Before the instance is destroyed.
Destroyed (): Called after the instance is destroyed. Everything indicated by the Vue instance is unbound, all event listeners are removed, and all subinstances are destroyed. The component has been completely destroyed, and all data, methods, filters, and instructions in the component are no longer available.
4. The application
These are all official instructions. How will these hook functions be used in a real development project?
Beforecreate: You can initialize the loading animation in this function
Created: Do some data initialization and implement function self-execution
Mounted: specifies whether to invoke a background interface to make network requests, retrieve data, and coordinate routing hooks
Destoryed: Deletes the current component
Navigation guard
Vue-router provides navigation guards that are used to guard navigation by jumping or canceling. There are multiple opportunities to implant routing during navigation, and they fall into three categories:
- Global routing guard: used in routing instance object registration;
router.beforeEach
router.beforeResolve
router.afterEach
- Route exclusive guard: item definition in route configuration item;
beforeEnter
- Routing guards within components: defined in component properties;
beforeRouteEnter
beforeRouteUpdate
beforeRouteLeave
1. beforeRouteLeave
Called when navigating away from the corresponding route of the component, we use it to prevent the user from leaving, for example, without saving the draft, or to destroy the setInterval before the user leaves, in case the timer is still invoked after the user leaves.
2. beforeEach
BeforEach is actually a vue-Router hook function and can be understood as a method that is called before every router jump
BeforEach three arguments:
- To: router Indicates the route object to be entered.
- From: Current navigation Route that is about to leave.
- Next: a function that must be called to resolve the hook. The execution depends on the call parameters of the next method.
next()
: Goes to the next hook in the pipe. If all hooks are executed, the navigation state is confirmed.next(false)
: interrupts current navigation. If the browser URL changes (either manually by the user or by the browser back button), the URL is reset to the address corresponding to the FROM route.- Next (‘/’) or next({path: ‘/’}): jumps to a different address. The current navigation is interrupted and a new navigation is performed.You can pass any location object to next, and you can set options like replace: true, name: ‘home’, and anything used in
router-link
Or to proprouter.push
Note that next can pass parameters through Query. next(error)
If the argument passed to Next is an Error instance, the navigation is terminated and the Error is passed torouter.onError()
Registered callback.
router.beforeEach((to, from, next) = > {
// Determine whether to filter routes according to the field
if (to.matched.some(record= > record.meta.auth)) {
if(getToken() ! = =null) {
next()
} else {
// Prevent infinite loops
if (to.name === 'login') {
next();
return
}
next({
path: '/login'}); }}else {
next()// If you click the page that does not need authentication, the route is redirected normally}});Copy the code
3. beforeRouteUpdate
Usage Scenarios:
Component reuse; Route jump;
beforeRouteUpdate (to, from, next) {
// Called when the current route changes but the component is being reused
// For a path with dynamic parameters such as /good/:id, when jumping between /good/1 and /good/2,
// Since the same GOOD component is rendered, the component instance is reused. And the hook will be called in that case.
// Access component instance 'this'
}
Copy the code
4. beforeEnter
You can define the beforeEnter guard directly on the route configuration:
const router = new VueRouter({
routes: [{path: '/foo'.component: Foo,
beforeEnter: (to, from, next) = > {
// ...}}}])Copy the code
5. beforeRouteEnter
The beforeRouteEnter route hook is triggered when you enter the home.vue page for the first time, but clicking on other menus in this page will not trigger, and we only need to initialize the menu when we enter it for the first time.
We can use the beforeRouteEnter routing hook to generate permission menus and store data in vuEX
We need to use beforeRouteEnter route hook in home. vue to generate permission menu and store permission data in vuex. First, on login. vue page, store the permission data returned by Login to local localStorage or sessionStorage. Then import the routing data in home.vue,
6. beforeResolve
Global resolution guard, similar to beforeEach, except that the resolution guard is called before navigation is acknowledged and after all components within the guard and asynchronous routing components have been resolved beforeEach and components within the beforeRouteEnter
The parameters are consistent with beforeEach, and you also need to call next to validate the navigation
7. afterEach
Global post-hooks that are called at the end of all route jumps do not accept the next function nor change the navigation itself
Complete navigation parsing process
- Navigation is triggered.
- Call the leave guard in the inactivated component
beforeRouteLeave
. - Call global
beforeEach
The guards. - Called in a reused component
beforeRouteUpdate
Guard (+ 2.2). - Called in the routing configuration
beforeEnter
. - Parse the asynchronous routing component.
- Called in the active component
beforeRouteEnter
. - Call global
beforeResolve
Guard (+ 2.5). - Navigation confirmed.
- Call global
afterEach
Hook. - Trigger a DOM update.
- Call with the created instance
beforeRouteEnter
Guard passnext
The callback function of.
Each guard method takes three arguments:
- To: Route: indicates the destination Route to be entered
- From: Route: indicates the Route that the current navigation is about to leave
- next: FunctionBe sure to call this methodresolveThis hook. Execution effect dependence
next
Method invocation parameters.- Next (): Goes to the next hook in the pipe. If all hooks are executed, the navigation state is confirmed.
- next(false): interrupts current navigation. If the browser URL changes (either manually by the user or by the browser back button), the URL is reset to
from
Indicates the IP address of the route. - Next (‘/’) or next({path: ‘/’}): Jumps to a different address. The current navigation is interrupted and a new navigation is performed. You can ask
next
Pass an arbitrary position object and allow setting such asreplace: true
,name: 'home'
And any other options used inrouter-link
的to
Prop orrouter.push
In. - next(error): (2.4.0+) If passed
next
The argument to is oneError
Instance, the navigation is terminated and the error is passed torouter.onError()
Registered callback.
Make sure you call the next method or the hook won’t be resolved.
Note:
beforeRouteEnter
Is the support tonext
The only guard that passes the callback. forbeforeRouteUpdate
和beforeRouteLeave
Speaking,this
It’s already available, soDoes not supportPass the callback because it is not necessary.
Properties and methods in VUE
let vm = new Vue({})
1. vm.$data
The data object observed by the Vue instance, which proxies access to its data object properties
2. vm.$el
The root DOM element used by the Vue instanceCopy the code
3. vm.$options
Initialization options for the current Vue instance that need to include custom attributes in the options are handled
Console. log(vm.$options) prints all mount entries on the VM
4. vm.$parent
Parent instance, if the current instance has one.
5. vm.$root
The root Vue instance of the current component tree, which is itself if the current instance has no parent
6. vm.$children
- A direct child of the current instance
- Note whether it is a child component or direct
- There’s no guarantee of order, and it’s not reactive
- If you find yourself trying to use $children for data binding, consider using an Array with V-fork to generate child components and Array as the real source
7. vm.$slot
- Used to access content distributed by slot, each named slot has a corresponding attribute
- The default attribute includes all nodes that are not included in slot
8. vm.$scopedSlots
To access Scoped slots
9. vm.$refs
和 ref
$refs
Is an object that represents all DOM elements and component instances that have registered the REF feature.
ref
Is used to register references to elements or child components that will be registered on the parent component’s $refs object. If used on a normal DOM element, it points to a normal DOM element.
Ref cannot set the same REF to multiple elements, only one can be recognized.
When v-for is used for elements or components, the reference information will be an array containing DOM nodes or component instances.
If you set a ref to the component, then you can get the instance of the component through this.$refs and call methods on the component instance.
Note: An important note about the ref registration time: since the Ref itself is created as a render result, you can’t access them during the initial render – they don’t exist yet! $refs is also not reactive, so you should not attempt to use it to do data binding in templates.
<body> <div id="app"> <template v-for=" I in 3"> <div ref="my"> my DOM element </div> </template> <my-component ref="com"></my-component> </div> </body> <script> let vm = new Vue({ el: "#app", mounted () { console.log(this.$refs.my); console.log(this.$refs.com.show()); }, components: {"myComponent":{template: '<div>my-component</div>'}}}) </script> Result: My DOM element my DOM element my-componentCopy the code
10. vm.$isServer
Whether the current instance is running on the server
11.vm.$props
- The props object received by the current component
- The Vue instance proxies access to properties of its props object
12. vm.$attrs
-
Contains feature bindings that are not recognized as prop in the parent scope, except for class and style
-
When a component does not declare any prop, it contains all parent scoped bindings, and the internal component can be passed in with v-bind=”$attrs “– useful when creating higher-level components
<script> // Parent component let vm = new Vue({el: "#app", data: {content: "I"}, // son component components: {"MyButton": // mounted(){// // this.$attrs // console.log(this.$attrs) //}, template: ` < div > subcomponents < my v - bind = "$attrs" > < / my > < / div > `, / / sun level component components: {' my ': {props: [' a', 'b'], the template: ` < span > component a sun {{a}} {{b}} - b < / span > `}}}}}) < / script > the result is: the subcomponents sun component a1, b2Copy the code
13. vm.$listeners
Contains time listeners in the parent scope, which can be passed into internal components via V-on =”$Listeners “– useful for creating higher-level components
14. Add instance attributes
- Data and instances used in many components, but you don’t want to pollute the global scope, can be made available in every Vue instance by defining them on the prototype
Vue.propotype.$appName='liba'
- AppName can then be used in all Vue instances, even before the instance is created
- Importance of setting scope for instance properties
15. vm.$watch
Syntax: vm.$watch(data,callback,[option]): used to monitor data changes
When the data is changed, the callback function can take two parameters, newValue and oldValue, as the value of the changed data, and the option option, which is an object {deep:true(false)}. Used to determine whether to monitor in depth (when monitoring data objects).
16. vm.$nextTick
- In the Vue life cycle
created()
DOM operations performed by hook functions must be placed inVue.nextTick()
In the callback function of $nextTick
The deferred callback is performed after the next DOM update loop is completed, after the data has been modified$nextTick
, you can get the updated DOM in the callback
17.vm.$emit
Triggers events on the current instance. Additional parameters are passed to the listener callback.
1. The parent component can use props to pass data to the child component. Child components can use $emit to trigger custom events for parent components.
$emit(event, arg)// Emit events on the current instance
vm.$on( event, fn ); // Run fn after listening for event events;
<div id="emit-example-simple"> <welcome-button v-on:welcome="sayHi"></welcome-button> </div> <script> Vue.component('welcome-button', { template: ` <button v-on:click="$emit('welcome')"> Click me to be welcomed </button> ` }) new Vue({ el: '#emit-example-simple', methods: { sayHi: function () { alert('Hi! ') } } }) </script>Copy the code
Ten, “”
1. Listenerswatch
The purpose of watch is to monitor the transformation of a value and call the methods that need to be executed because of the change. You can change the state of the association dynamically through Watch.
<script> let vm = new Vue({el: "#app", data: {MSG: "adadsad"}, watch: { Function (newvalue, oldvalue) {console.log(newvalue, oldvalue)}}}) vm. MSG = "2222"Copy the code
Note that you should not use the arrow function to define the Watcher function (for example searchQuery: newValue => this.updateAutoComplete (newValue)). The reason is that the arrow function is bound to the context of the parent scope, so this will not point to the Vue instance as expected, and this.updateAutocomplete will be undefined.
Note: Watch can support asynchracy. Other cases and computed are interchangeable, but watch is more complicated to write. Watch can perform some simple functions.
2. Interceptors
Intercepts requests or responses before they are processed by THEN or catch.
/ / add request interceptor axios. Interceptors. Request. Use (function (config) {/ / what to do before sending a request return config. }, function (error) {return promise.reject (error); }); / / add the response interceptor axios. Interceptors. Response. Use (function (response) {/ / do something to return the response to the response data; }, function (error) {return promise.reject (error); });Copy the code
If you want to remove interceptors later, you can do this:
var myInterceptor = axios.interceptors.request.use(function() {/ *... * /}); axios.interceptors.request.eject(myInterceptor);Copy the code
You can add interceptors for custom AXIOS instances
var instance = axios.create(); instance.interceptors.request.use(function () {/*... * /});Copy the code
3. Data hijacking
let obj = {
name:'z3'.age: {age:55}}function observer(obj){
if(typeof obj == "object") {for (let key inobj){ defineReactive(obj,key,obj[key]); }}}function defineReactive(obj,key,value){
Object.defineProperty(obj,key,{
get(){
return value
},
set(val){
console.log("Data Update")
value = val;
}
})
}
observer(obj);
obj.name = "wc"
console.log(obj.name)
Copy the code