Vue basis
- Encounter Vuejs
- 1. Know Vuejs
- 2. At the beginning of the Vue experience
- 3. The MVVM Vue
- 4. Options passed in the Vue instance
- 5.Vue life cycle
- The interpolation instruction
- 1.Mustache
- 2.v-once
- 3.v-html
- 4.v-text
- 5.v-pre
- 6.v-cloak
- conclusion
- V-bind Indicates the binding attribute
- 1. V – bind is introduced
- 2. V – bind binding class
- 3. V – bind binding style
- Computed attribute
- 1. Basic concepts
- 2. Calculate the setter and getter of the property
- 3. Calculate the cache of attributes
- Event listen instruction
- 1. V – on parameters
- 2. V – on the modifier
- Conditional render instruction
- 1. Vi-f vs. V-else-if vs. V-else
- 2. Reuse element rendering problem
- 3.v-show
- Loop through instructions
- 1. V-for traversal group
- 2. V-for traversal objects
- 3. Key attribute in Vue
- 4. Array reactive methods
- 5.Vue.set Modifies reactive data
- 6. V – if and v – for
- Form binding v-Model
- 1. Basic concepts
- 2. V – model principle
- 3. Bind the form to v-Model
- 4. Bind v-Model to other types in the form
- 5. Value binding
- 5. V-model modifier
- Vue Common features
- 1. Customize instructions
- 2. Watch the listener
- 3. The filter
- 4. Life cycle
Encounter Vuejs
1. Know Vuejs
- Vue is a progressive framework. What is progressive?
- Declarative rendering → component system → client routing → centralized state management → project building
- Incremental means you can embed Vue as part of your application, resulting in a richer interactive experience.
- Vue has many features and advanced features common in Web development
- Decouple views and data
- Reusable components
- Front-end routing technology
- State management
- Virtual DOM
2. At the beginning of the Vue experience
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<! Import Vue package --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script> </head> <body> <! < div div > < div div > <div id="app"> {{message}} </div> </body> <script> // 2, create a Vue instance var app = new Vue({ el: '#app'.// Used to mount the elements to be managed data: {// Define the data message: 'learning Vue. Js } }); </script> </html> Copy the code
3. The MVVM Vue
- The View layer
- The view layer
- In front end development, it’s usually the DOM layer
- The main function is to present various information to the user
- Model layer
- The data layer
- The data may be dead data that we have fixed, but more often than not, it’s data that comes from our servers, requests from the network
- VueModel layer
- View model layer
- View Model layer is the bridge between View and Model
- On the one hand, it implements a Data Binding, which reflects changes to the Model to the View in real time
- On the other hand, it implements the DOM Listener, that is, the DOM Listener, when the DOM occurs some events (click, scroll, touch, etc.), can listen to and change the corresponding Data in case of need.
4. Options passed in the Vue instance
- Now,
The property name | type | role |
---|---|---|
el |
Type: string | HTMLElement | Determines which DOM the Vue instance will manage |
data |
Type: Object | Function (component of the data must be a Function) | The data object corresponding to the Vue instance |
methods |
Type: {[key: string]: Function} | Defines methods that belong to Vue and can be called from elsewhere or used in directives |
5.Vue life cycle
The official figure
The interpolation instruction
1.Mustache
- Interpolation {{}}
The most common form of data binding is text interpolation using Mustache syntax (double braces). Such as:
<span>Message: {{ msg }}</span> Copy the code
The Mustache tag will be replaced with the value of the MSG attribute (MSG is defined in the data object) on the corresponding data object.
Whenever the MSG property changes on the bound data object, the contents at the interpolation are automatically updated.
grammar | {{}} JavaScript expression support |
---|---|
Ordinary expression | {{ number + 1 }} |
Ternary expression | {{ ok ? ‘YES’ : ‘NO’ }} |
Ternary expression | {{ name == ‘smyhvae’ ? ‘true’ : ‘false’ }} |
A method is called | {{ message.split(”).reverse().join(”) }} |
2.v-once
This directive does not need to be followed by any expression. This directive indicates that the element is rendered only once and does not change as the data changes.
<h2 v-once>{{message}}</h2>
Copy the code
3.v-html
Parse the HTML code in the data and render it to the page
<h2 v-html="url"></h2>
Copy the code
4.v-text
V-text is similar to Mustache: Both are used to display data in the interface, except that V-text is written in an attribute. V-text usually receives a string
<h2 v-text="text"></h2>
Copy the code
5.v-pre
The V-pre is used to skip the compilation of this element and its children and to show the original Mustache syntax.
<h2 v-pre>{{message}}</h2>
Copy the code
6.v-cloak
In some cases, our browser may simply display the uncompiled Mustache tag. The CLOAK directive, when used with the CSS rule, solves the problem of interpolation flickering (i.e. uncompiled tags can be hidden until the instance is ready).
<! Before vue parsing, there is a cloak attribute in the divAfter vue parsing, there is no v-cloak attribute in the div
<div id="app" v-cloak>
<h2>{{message}}</h2>
</div>
Copy the code
conclusion
- Mustache: {{}} syntax, you can write variables/logical expressions/calculated values…
- V-once: Elements are rendered only once and do not change as the data changes.
- V-html =”” : Parse the HTML code in the data and render it to the page
- V-text =” MSG “: write in the property to display the data in the interface
- V-pre: Original output showing original Mustache syntax
- V-cloak: This cloak is usually used with CSS rules to solve interpolation flicker problems
V-bind Indicates the binding attribute
1. V – bind is introduced
- The instructions we studied earlier are primarily used to insert values into the content of our template.
- However, in addition to content that needs to be determined dynamically, some properties also want to be bound dynamically.
- Function: You can dynamically bind one or more features to an HTML element or component, such as dynamic binding
style
andclass
- For example, dynamically bind the a element’s href attribute
- For example, dynamically bind the SRC attribute of the img element
- At this point, we can use the V-bind directive:
- Function: Dynamically bind properties
- abbreviations:
:
- Expectation: any (with argument) | Object (without argument)
- Parameter: attrOrProp (optional)
2. V – bind binding class
There are two ways to bind a class
- Object syntax
- Array syntax
- Object syntax
- Object syntax means
:class
It’s followed by an object.
- Object syntax means
<! Bind a class directly to {} -->
<h2 :class="{'active': isActive}">Hello World</h2>
<! You can also pass in multiple values by judgment -->
<h2 :class="{'active': isActive, 'line': isLine}">Hello World</h2>
<! Exist at the same time as an ordinary class --> <! If both isActive and isLine are true, then there are three classes: title, active, and line --> <h2 class="title" :class="{'active': isActive, 'line': isLine}">Hello World</h2> <! If it is too complex, use methods or computed --> <! Classes is a computed property --> <h2 class="title" :class="classes">Hello World</h2> Copy the code
- Array syntax
- Array syntax means
:class
It’s followed by an array.
- Array syntax means
<! -- 1. ['active','news'] -->
<h2 class="title" :class="['active','news']">{{message}}</h2>
<! -- [active, new] -->
<h2 class="title" :class="[active,news]">{{message}}</h2>
<! --> --> --> -->
<h2 class="title" :class="getClasses()">{{message}}</h2> Copy the code
3. V – bind binding style
-
We can use v-bind:style to bind some CSS inline styles
-
There are two ways to bind a class
- Object syntax
- Array syntax
-
Object syntax
style
This is followed by an object type- The object’s
key
Is the name of the CSS property - The object’s
value
Is a specific value assigned, which can be fromdata
The properties in the
:style= {" "color: currentColor, fontSize: fontSize + 'px'}"
Copy the code
- Array syntax
style
This is followed by an array type, multiple values separated by,
<div v-bind:style="[baseStyles, fontColor]"></div>
/* js */
baseStyle: {background: 'lime'},
fontSize: {fontSize: '80px'}
Copy the code
Computed attribute
1. Basic concepts
-
Computed attributes appear to address the problem that putting too much logic into a template can make the template overweight and difficult to maintain
-
Computed properties are cached based on their responsive dependencies
-
In some cases, we may need to do some transformation of the data before display, or we may need to combine multiple data for display
- For example, we have
firstName
andlastName
We need to display the full names of the two variables. - But if the full name needs to be displayed in more than one place, we need to write more than one
{{firstName}} {{lastName}}
- For example, we have
-
Convert the above code into a computed property
/* html */ <h2>{{fullNmae}}</h2> /* js */ computed: { fullNmae: function () { return this.firstNmae + ' ' + this.lastNmae; } } Copy the code
2. Calculate the setter and getter of the property
- Each computed property contains one
getter
And asetter
- In the example above, we just used
getter
To read. - In some cases, you can also provide a setter method (not often).
- When you need to write a setter, the code looks like this:
- In the example above, we just used
Begin to see
3. Calculate the cache of attributes
- Methods Differences between methods and computed
methods
The function executes whenever it is called, regardless of whether the data has changed or not. (Sometimes we don’t want to call the function if the data hasn’t changed.)computed
The evaluated properties are cached, and the function is called only once if the data has changed.
- Conclusion:
methods
The function is called regardless of whether the data has changedcomputed
The function is called back only if the dependent data has changed
Event listen instruction
- In front end development, we need to interact with users frequently
- At this point, we have to listen to the user’s occurrence time, such as click, drag and drop events, etc
- V – on is introduced
- Function: Bind event listeners
- Abbreviations:
@
1. V – on parameters
- when
methods
Defines methods in the@click
When calling, you need to pay attention to parameters - Case 1: If the method does not require additional parameters, the method after
(a)
Can be omitted- No parameters are passed, and the default when receiving a parameter is a native event
event
Parameter passed in
- No parameters are passed, and the default when receiving a parameter is a native event
- Case 2: If you need to pass a parameter at the same time, you need to
event
, you can pass$event
Incoming events
2. V – on the modifier
v-on
A number of event modifiers are provided to assist in implementing some functionality. Event modifiers are as follows
The modifier | role |
---|---|
.stop | Stop bubbling. To call Event.stopPropagation () |
.prevent | PreventDefault event behavior by calling event.preventdefault () |
.{keyCode | keyAlias } | The callback is fired when the event is fired from a specific key |
.once | The event is triggered only once |
Conditional render instruction
1. Vi-f vs. V-else-if vs. V-else
- Vue’s conditional directives can render or destroy elements or components in the DOM based on the value of the expression
<h2 v-if="score>=90">good</h2>
<h2 v-else-if="score>=80">good</h2>
<h2 v-else-if="score>=60">Pass the</h2>
<h2 v-else>Don't pass the</h2>
Copy the code
- You are advised not to use this parameter in the template because there is too much logic
v-if-else-if
2. Reuse element rendering problem
A question: It involves the underlying Vue. After clicking the virtual DOM to switch the form, the input value is not cleared. Why?
- Elicited: Switch when realized by clicking the button
input
Form, we enter onvalue
When you click the button to switch formsvalue
The value is still there, butinput
The elements do switch, and why?
<span v-if="isUser">
<label for="user">The user name</label>
<input type="text" placeholder="User name" id="user" key="user">
</span>
<span v-else>
<label for="email">email</label> <input type="text" placeholder="Email" id="email" key="email"> </span> <button @click="isUser=! isUser">Switch type</button> <script> const app = new Vue({ el: '#app'. data: { isUser: true } }) </script> Copy the code
- The reason:
- 1. This is because Vue will reuse existing elements as much as possible instead of creating new elements for the sake of performance when making DOM rendering
- 2. In the above case, Vue will compare internally and find that both parts are similar. It will only replace the attributes, not create a new element for you
- 3. If input is no longer used. Else input is used directly
- The solution
- If we don’t want to
Vue
Problems like reuse can be given to the correspondinginput
addkey
- 2. And make sure you get what you need
key
Different, this wayvue
It creates a new oneinput
The element
- If we don’t want to
3.v-show
V-show is used much like V-if to determine whether an element is rendered or not
- V-if versus V-show
- V-if when the condition is false, there is no corresponding element in the DOM at all
- V-show When the condition is false, it simply sets the element’s display attribute to None
- How to choose in development?
- Use V-show when you need to switch between show and hide very frequently
- By using v-if when there is only one switch
<h2 v-show="isShow">{{message}}</h2>
Copy the code
Loop through instructions
1. V-for traversal group
- Function: Generate content by traversing the specified template content according to the elements in the array.
- Grammar:
v-for="(item, index) in items"
<ul>
<! -- item: is each element index: index -->
<li v-for="(item, index) in name">
{{index+1}}.{{item}}
</li>
</ul> Copy the code
2. V-for traversal objects
- Function: To iterate over objects
- Grammar:
v-for="(value, key, index) in items"
<ul>
<! -- value: attribute value key: attribute name index: index -->
<li v-for="(value, key, index) in info">
{{index+1}}.{{value}}
</li>
</ul> Copy the code
3. Key attribute in Vue
- Official recommendation we are using
v-for
Is added to the corresponding element or component:key
Properties. - Why do you need this key attribute?
- This is actually the same as Vue’s virtual DOM
Diff
The algorithm matters.
- This is actually the same as Vue’s virtual DOM
- When there are many of the same nodes on a layer, that is, list nodes, we want to insert a new node
- We want to be able to put an F between B and C, which is what Diff does by default.
- Is it inefficient to update C to F, D to C, E to D, and then insert E?
- So we need to use the key to uniquely identify each node
- Diff algorithm can correctly identify this node
- Find the correct location area to insert the new node
- Key is used to update the virtual DOM efficiently
When v-for is used to update a rendered list of elements, the in-place reuse policy is used by default. If the list data is modified, it will determine whether a value is modified according to the key value. If it is modified, it will re-render this item, otherwise it will reuse the previous element. We often use index(the index of an array) as the key, but this is not recommended;
4. Array reactive methods
- Because Vue is responsive, when the data changes, Vue will automatically detect the change and the view will be updated accordingly
- Vue contains a set of methods for observing the compilation of an array. Making them change the array also triggers an updated view
- push()
- pop()
- shift()
- unshift()
- splice()
- sort()
- reverse()
5.Vue.set Modifies reactive data
Vue.set(vm.items, indexOftem, newValue)
vm.$set(vm.items ,indexOften,newValue)
- Parameter 1: The array/object to be modified
- Parameter 2: The index to set/the name of the property to add
- Parameter 3: set value
6. V – if and v – for
When they are on the same node, V-for has a higher priority than V-IF, which means
V-if is repeated separately for each V-for loop.
Avoid using v-if and V-for together
- why
- If the if judgment is used, each rendering inside the Vue traverses the entire list, regardless of whether the judgment conditions have changed
- Benefits of using computed attributes
- 1. The filtered list will be evaluated only when the Users array changes, which makes filtering more efficient.
- 2. Use v-for=” User in ActiveUsers “after we render
- 3. Only traverses active users, rendering more efficiently.
- 4. Decoupled rendering layer logic, more maintainability (changes and extensions to the logic).
- Detailed interpretation of the
Form binding v-Model
1. Basic concepts
- Used in the Vue
V - model instruction
To implement bidirectional binding of form elements and data- The data and the template interact with each other; when one changes, the other updates immediately
- Lead:
- In the previous case, we used v-bind to bind the name attribute in the data object to the tag. The tag is automatically updated when the value of name in data changes.
- Here’s what to do: Change the content in the <input> tag to require that the value of the name attribute in data be automatically updated. To achieve two-way data binding. How do you do that? That’s what you can use
v-model
This property.
- The difference between:
v-bind
: Can only implement one-way data binding, automatically binding data from M to V.v-model
: onlyv-model
To achieve bidirectional data binding. Pay attention to,V - after the model
Noodles do not need to follow a colon
- Pay attention to
v-model
Can only be used in form elements, or for custom components. Common form elements include:input(radio,text,address,email...) ,select, checkbox, textarea.
2. V – model principle
- V-model is actually a grammatical sugar, and the essence behind it is that it contains two operations
- V-bind binds a value attribute
- The V-ON directive binds the input event for the current element
- This is equivalent to the following code:
<input type="text" v-model="message">
<! -- equivalent to the following code -->
<input type="text" :value="message" @input="message = $event.target.value">
Copy the code
3. Bind the form to v-Model
- Used in the Vue
v-model
Directive to implement bidirectional binding of form elements and data - Case study:
- When we enter something in the data box
- Because the V-Model in the input is bound with message, the input content will be passed to the message in real time, and the message will change
- When message changes, the DOM changes in response because we inserted the message value into the DOM using the Mustanche syntax above
- Therefore, bi-directional binding is achieved through v-Model
- Of course, we can use the V-Model for textarea elements
1. Bind the form to the V-Model
2. The textarea binding v – model
4. Bind v-Model to other types in the form
- Other types in the form, bindings
v-model
Form type | Single/multiple options | The value of the binding |
---|---|---|
v-model: radio |
Multiple checkboxes | The binding ofValue is the value |
v-model: checkbox |
Single check box | V – model isBoolean value |
Multiple check boxes | Select multiple, correspondingdata Property is aAn array of |
|
v-model: select |
The radio | v-model It’s bound to onevalue |
multi-select | v-model It’s bound to oneAn array of |
v-model: radio
v-model: checkbox
v-model: select
5. Value binding
- Dynamic to
value
Assignment”- We wrote it before
value
Is given directly in defining the input - But in real development, these values in the input might be taken from the server and then defined
- So we can go through
v-bind:value
Dynamically bind value to value
- We wrote it before
Value binding
5. V-model modifier
The modifier | role |
---|---|
.lazy |
When the formLose focus Or press theenter When,data Is updated |
.number |
The input is converted tonumber The data type |
.trim |
Filter content on both sidesThe blank space |
Vue Common features
1. Customize instructions
- Why do you need custom directives
- The built-in instructions are not sufficient
Directive registers global directives
- Custom instruction syntax (get focus)
Vue.directive('focus', {
inserted: function (el) {
el.focus()// Get the focus of the element
}
})
// Use custom instructions <input type="text" v-focus> Copy the code
- Custom instructions with parameters
Vue.directive('color', {
// bind declares a cycle that is called only once, the first time a directive is bound to an element. This is where you can do one-time initialization
// el is the DOM element of the current custom directive
// Binding for a custom function parameter. The value passed by the custom property is contained in binding
bind: function(el, binding){
// Set the background color according to the parameters of the command // console.log(binding.value.color) el.style.backgroundColor = binding.value.color; } }); // Use a custom directive with parameters <input type="text" v-color='msg'> Copy the code
Custom local instructions
- Local instructions need to be defined in
directives
The option usage is the same as the global usage - Local directives can only be used within the current component
- When a global instruction and a local instruction have the same name, the local instruction prevails
directives: {
focus: {
inserted: function(el) {
el.focus();
}
} } Copy the code
2. Watch the listener
- Application scenarios of listeners
- Executed when data changes
asynchronous
orAn expensive operation
- Note: Properties in watch must be data that already exists in data
// When the: firstName or lastNames attribute in the data changes, the corresponding watch is automatically triggered
watch: {
firstName(val) { // val: indicates the changed value
this.fullName = val + ' ' + this.lastName;
},
lastName(val) { this.fullName = this.firstName + ' ' + val; } } Copy the code
3. The filter
Concept: Vue.js allows us to customize filters that can be used for some common text formatting/processing.
Filters can be used in two places: mustache interpolation and V-bind expression.
Filters should be added at the end of JavaScript expressions, indicated by the “pipe” character.
Filters do not change the actual data, but only the rendered results and return the filtered version
- Global registration is filter, no s. Local filters are filters, and they have s
- Support for cascading operations (filtering the previously filtered data again)
Custom global filters
- We can do it globally
Vue.filter()
Customize a global filter. In this case, every instance of a Vue object (Each VM instance
) can get this filter. It receivesTwo parameters
:Name of the filter
,Filter function
.
<div>{{msg | upper}}</div>
<div>{{msg | upper | lower}}</div>
<div :class="msg | upper"></div>
<! -- with parameter filter -->
<div>{{date | format('yyyy-MM-dd')}}</div>
<script> // 1. Global filter Vue.filter('upper', (val) => { // val is the data to be processed return val.charAt(0).toUpperCase() + val.slice(1); }) // 2. Processing with parameter filter Vue.filter('format', (date, arg) => { // arg: parameter passed if (arg === 'yyyy-MM-dd') { return date.getFullYear() + The '-' + (date.getMonth() + 1) + The '-' + date.getDate(); } }) </script> Copy the code
Custom private filters
- Private filters: Filters defined within a Vue object are called private filters
- This filter is only available in
Current vUE object
theRegulatory area designated by EL
Useful.
<! -- price before pipe: to filter the price text -->
<! ShowPrice: is operated through the showPrice filter -->
<td>{{price | showPrice}}</td>
<script>
const app = new Vue({ filters: { showPrice(price) { return A '$' + price.toFixed(2); } } }) </script> Copy the code
4. Life cycle
-
The process from birth to death
-
The process of creating a Vue instance and destroying it is accompanied by some self-calling functions. We call these functions hook functions
-
The main stage
-
Mount (initialize related properties)
- beforeCreate
- created
- beforeMount
- mounted
-
Update (a change operation to an element or build)
- beforeUpdate
- updated
-
Destroy (destroy related properties)
- beforeDestroy
- destroyed
Hook function | process |
---|---|
beforeCreate | It’s called after the instance is initialized, before the data observation and event configuration at which point the data and methods and the DOM structure of the page are not initialized and nothing can be done, okay |
created | It’s called immediately after the instance has been created when data and methods are available but the page has not yet been rendered |
beforeMount | It’s called before the mount starts and you don’t have any real data on the page yet it’s just a template page |
mouted | El is replaced by the newly created VM.$el, and the hook is called after the instance is mounted. The data is actually rendered to the page and we can use some third party plug-ins in this hook function |
beforeUpdate | Called when data is updated, before the virtual DOM is patched. The data on the page is still old |
update | This hook is called after the virtual DOM is rerendered and patched due to data changes. The data on the page has been replaced with the latest one |
beforeDestroy | Called before instance destruction |
destroyed | Called after instance destruction |