examineOriginal site, more expanded content and better reading experience!
Vue foundation
Root instance of constructor Vuenew Vue({})
And start the Vue application.
var app = Vue({
el: "#app",
data: {},
methods: {}
});
Variableapp
On behalf of this Vue instance.
Among them, the essential options areel
A that specifies a DOM element that already exists in a page to mount a Vue instance, which can beHTMLElement
, or CSS selectors.
var app = Vue({
el: document.getElementById('app')
});
After the mount is successful, you can use theapp.$el
Access this element. Vue provides many commonly used instance properties and methods, all of which are based on$
The beginning.
data
Option is used to declare data that requires bidirectional binding within the application. It is recommended that all data to be used should be available in advancedata
Internal statement, improve the maintainability of the business.
Vue instancenew Vue({})
, which can be used hereapp
Actingdata
All properties in the object can be accessed as followsdata
Data in:
console.log(app.name);
In addition to explicitly declaring data, it can also point to an existing variable, and a two-way binding is established between them by default. When any one is modified, the other will also change accordingly.
var myData = {
a: 1
};
var app = Vue({
el: "#app",
data: myData
});
app.a = 2;
console.log(myData.a);//2
myData.a = 3;
console.log(app.a);//3
Life cycle
Vue’s Lifecycle Hook:
-
created
: Called after the instance is created. Data observation is completed at this stage, but not mounted.$el
Not yet available. (This is useful when initialization is required to process some data) -
mounted
:el
Called after being mounted on the instance, the first business logic starts here. -
beforeDestroy
: Called before the instance is destroyed. Mainly untie some useaddEventListener
Monitoring events, etc.
These hooks are associated withel
Anddata
Similarly, it is also written into Vue instance as an option and hookedthis
Pointing to the Vue instance that called it.
Interpolation and Expression
Use (Mustache syntax){{}}
Is the most basic text interpolation method, it will automatically display our two-way bound data in real time.
v-html
Directly output HTML instead of parsed plain text.
<div id="app">
<span v-html="link"></span>
</div>
new Vue({
el: "#app",
data: {
link: '<a href="#">this is a link.</a>'
}
});
Link’s content will be rendered into aa
Tags, not plain text.
If user-generated content is usedv-html
After the output, it may lead to XSS attack, so to process the content submitted by the user at the server, you can generally<>
Escape.
If you want to display{{}}
Label, without replacement, usev-pre
You can skip the compilation of this element and its child elements.
- In
{{}}
In addition to simple binding attribute values, JavaScript expressions can also be used for simple operations, ternary operations, etc. - Vue supports only a single expression, not statements and process control.
- User-defined global variables cannot be used in expressions, only global variables in Vue whitelist can be used, for example
Math
AndDate
.
Filter
Vue.js supports{{}}
Add a pipe character to the end of the interpolation(|)
Filter data, often users format text, such asAll letters are capitalized、Currency thousands are separated by commasWait. The filtering rules are customized by adding options to Vue instancesfilter
To set.
<div id="app">
{{date | formatDate}}
</div>
Filters can also be connected in series and can receive parameters:
<!--串联-->
{{message | filterA | filterB}}
<!--接收参数-->
{{message | filterA('arg1','arg2')}}
Filters should be used to handle simple text transformations, and if more complex data transformations are to be implemented, computational properties should be used.
Command event
Instruction (Directives
) is the most commonly used function in Vue.js templates, which is prefixed withv-
. The main responsibility of an instruction is to apply certain behaviors to the DOM when the value of its expression changes.
v-bind
The basic purpose of is to dynamically update attributes on HTML elements, such asid
、class
Wait.
Another very important instruction isv-on
A used to bind event listeners.
On common elements,v-on
You can listen for native DOM events exceptclick
There are alsodbclick
、keyup
、mousemove
Wait. An expression can be a method name, and these methods are written in Vue citymethods
Property and is in the form of functions whosethis
Pointing to the current Vue instance itself, it can be used directly.this.xxx
To access or modify data in the form of.
Vue.js willmethods
In the method of proxy, can like access Vue data call method:
<div id="app">
<p v-if="show">这是一段为本</p>
<button @click="handleClose">点击隐藏</button>
</div>
new Vue({
el: "#app",
data: {
show: true
},
methods: {
handleClose: function () {
this.close()
},
close: function () {
this.show = false
}
}
});
InhandleClose
Through the method directlythis.close()
Calledclose()
Function.
var app = new Vue({
el: "#app",
data: {
show: true
},
methods: {
init: function (text) {
console.log(text);
},
},
mounted: function () {
this.init('在初始化时调用');
}
});
app.init('通过外部调用');
syntactic sugar
Grammatical sugar refers to adding a method to achieve the same effect without affecting the function, thus facilitating program development.
Vue.jsv-bind
Andv-on
Instructions all provide grammatical sugar, or abbreviations, such asv-bind
Abbreviated as:
, mostly fora
、img
Label;v-on
Abbreviated as@
Forinput
、button
Label.
Calculation attribute
All calculated attributes are written in Vue instances as functionscomputed
Option, finally return the calculated results.
Usage of computed attributes
All kinds of complicated logic can be completed in a calculation attribute, including operations, function calls, etc., as long as a result is finally returned.
The calculation attribute can also depend on the data of multiple Vue instances. As long as any data changes, the calculation attribute will be re-executed and the view will be updated.
Each computed attribute contains agetter
And onesetter
.
In most cases, only the default will be usedgetter
The method reads a calculation attribute, which is rarely used in businesssetter
, so when you declare a calculated attribute, you can use the default writing method directly. you do not need togetter
Andsetter
Both declared.
Besides simple text interpolation, computational attributes are often used to dynamically set the style names of elements.class
And inline stylesstyle
. When using components, computed properties are also often used for dynamic passingprops
.
There are also two practical tips for calculating attributes that are easily overlooked:
- First, the calculation attribute can depend on other calculation attributes;
- Second, the calculation attribute can not only depend on the data of the current Vue instance, but also on the data of other instances.
<div id="app1"></div>
<div id="app2">
{{reverseText}}
</div>
var app1 = new Vue({
el: "#app1",
data: {
text: '123,456'
},
});
var app2 = new Vue({
el: "#app2",
computed: {
reverseText: function () {
//这里依赖的是实例app1的数据text
return app1.text.split(',').reverse().join(',');
}
}
});
Calculate attribute cache
No calculation attribute is used, inmethods
A method is defined in to achieve the same effect. Even the method can accept parameters and is more flexible to use.
The reason for using a computed attribute is its dependency cache.. When the data on which a calculation attribute depends changes, it will re-take the value. In the above example, as long astext
If the value does not change, the calculation attribute will not be updated. butmethods
It is different, as long as it is re-rendered, it will be called, so the function will also be executed.
Do you use calculated properties ormethods
Depending on whether you need caching or not, when traversing large arrays and doing a large number of calculations, you should use calculation properties unless you do not want caching.
v-bind
Andclass
Andstyle
Binding
v-bind
The main use of is to dynamically update attributes on HTML elements.
In data binding,v-bind
The two most common applications are the style names of elementsclass
And inline stylesstyle
The dynamic binding of.
Bindingclass
Several ways of
Object syntax
tov-bind:class
Set an object that can be switched dynamicallyclass
:
<div id="app">
<div :class="{'active':'isActive'}">测试文字</div>
</div>
new Vue({
el: "#app",
data: {
isActive: true
},
});
Objects can also be passed in multiple attributes to switch dynamicallyclass
. In addition,:class
Can be compared with ordinaryclass
Coexistence.
<div class="static" :class="{'active':'isActive','error':isError}">测试文字</div>
data: {
isActive: true,
isError: false
}
When:class
If the expression of is too long or the logic is complex, you can also bind a calculation property. When there are more than two conditions, both can be useddata
Orcomputed
.
In addition to calculating attributes, you can also directly bind data of type Object, or use a that is similar to calculating attributes.methods
.
Array syntax
When multiple applications are requiredclass
You can use array syntax to:class
Bind an array, apply anclass
List:
<div id="app">
<div :class="[activeCls,errorCls]">测试文字</div>
</div>
new Vue({
el: "#app",
data: {
activeCls: 'active',
errorCls: 'error'
}
});
// 结果
<div class="active error">测试文字</div>
You can also use ternary expressions to switch according to conditionsclass
:
<div :class="[isActive ? activeCls : '',errorCls]">测试文字</div>
new Vue({
el: "#app",
data: {
isActive: true,
activeCls: 'active',
errorCls: 'error'
}
});
Whenclass
When there are multiple conditions, you can use object syntax in array syntax:
<div id="app">
<div :class="[{'active':isActive},errorCls]">测试文字</div>
</div>
Using computation attributes to dynamically set class names for elements is often used in business, especially when writing reusable components, so in the development process,If the expression is long or the logic is complex, the evaluation attribute should be used as preferentially as possible..
Used in Components
If used directly on custom componentsclass
Or:class
, style rules are applied directly to the root element of this component.
Vue.component('my-component', {
template: `<p class="article">一些文本</p>`
});
Then when this component is called, the object syntax or array syntax is applied to bind the component.class
:
<div id="app">
<my-component :class="{'active':isActive}"></my-component>
</div>
This usage is only applicable to custom components where the outermost layer is a root element, otherwise it will be invalid. When this condition is not met or a class name needs to be set for a specific child element, the of the component should be usedprops
To deliver.
Binding inline style
Use:style
You can bind inline styles, methods, and:class
Similarly, there are also object syntax and array syntax, much like writing CSS directly on elements.
<div id="app">
<div :style="{'color':color, 'fontSize':fontSize+'px'}">文本</div>
</div>
new Vue({
el: "#app",
data: {
color: 'red',
fontSize: 14
}
});
The style is usually written indata
Orcomputed
Medium:
<div id="app">
<div :style="styles">文本</div>
</div>
new Vue({
el: "#app",
data: {
styles: {
color: 'red',
fontSize: 16 + 'px'
}
}
});
In actual business,:style
The array syntax of is not commonly used and can be written in an object, while the more commonly used is to calculate attributes.
In addition, use:style
Vue.js will automatically prefix special CSS attribute names, such astransform
.
Built-in instruction
Basic instruction
v-cloak
v-cloak
No expression is required, it will be removed from the bound HTML element at the end of compilation of the Vue instance, often with CSSdisplay: none;
Cooperate with:
<div id="app" v-cloak>
{{message}}
</div>
When the network speed is slow and the Vue.js file has not been loaded, it will be displayed on the page{{message}}
The DOM will not be replaced until Vue creates the instance and compiles the template, so the process screen will flash. Just add a CSS to solve this problem:
[v-cloak] {
display: none;
}
V-cloak is a best practice to solve the problem of page flicker caused by slow initialization, which is very practical for simple projects.
In an engineering project, the HTML structure of the project is only emptydiv
Element, the rest is done by routing and mounting different components, which is no longer needed.v-cloak
.
v-once
v-once
Is an instruction that does not require an expression. Its function is to define its element or component to render only once, including all child nodes of the element or component. After the first rendering, it will not be re-rendered with the change of data and will be regarded as static content.
v-once
It is rarely used in business and may be used if further performance optimization is needed.
Conditional rendering instruction
v-if
、v-else-if
、v-else
The conditional instruction of Vue.js can render or destroy elements/components in DOM according to the value of expression.
v-else-if
Follow closelyv-if
,v-else
Follow closelyv-else-if
Orv-if
When the value of the expression is true, the current element/component and all child nodes will be rendered and removed when false.
If more than one element is judged at a time, it can be built in Vue.js<template>
A conditional instruction is used on the element, and the final rendered result will not include the element.
Vue is considering efficiency when rendering elements and will reuse existing elements as much as possible instead of re-rendering.
<div id="app">
<template v-if="type==='name'">
<label>用户名:</label>
<input type="text" placeholder="输入用户名">
</template>
<template v-else>
<label>邮箱:</label>
<input type="text" placeholder="输入邮箱">
</template>
<button @click="handleToggleClick">切换输入类型</button>
</div>
new Vue({
el:"#app",
data:{
type:'name'
},
methods:{
handleToggleClick:function(){
this.type=this.type==='name'?'mail':'name';
}
}
})
In the example, after typing the content, click the switch button. Although DOM has changed, what was typed in the input box has not changed but has been replaced.placeholder
The content and description of<input>
Elements are reused.
Using Vue.jskey
Attribute allows you to decide whether to reuse elements or not.key
The value of must be unique.
<input type="text" placeholder="输入用户名" key="name-input">
Give two<input>
The elements have all increasedkey
After that, it will not be reused. What you type when switching types will also be deleted, however<label>
Elements will still be reused because they have not been addedkey
Property.
v-show
v-show
The usage of andv-if
Basically the same, butv-show
Is to change the CSS properties of an elementdisplay
.
Whenv-show
The value of the expression isfalse
When elements are hidden, DOM structural elements are loaded with inline stylesdisplay:none;
.
v-show
Not in<template>
Use on.
v-if
Andv-show
The choice of
v-if
Andv-show
It has similar functions, howeverv-if
Is the real conditional rendering, it will be appropriate according to the expressionDestroy or rebuildElements and bound events or subcomponents.
If the initial value of the expression isfalse
, the element/component will not render initially and compilation will only begin when the condition becomes true for the first time.
Andv-show
Just a simple CSS property switch, whether the condition is true or not, will be compiled.
In contrast,v-if
It is more suitable for scenes where conditions do not change frequently, because its switching overhead is relatively large, whilev-show
Applicable to frequent switching conditions.
List rendering instructionv-for
Basic usage
List rendering instructions are used when it is necessary to iterate through an array or enumerate an object for circular display.v-for
. Its expressions need to be combinedin
To use, similar toitem in items
The form of.
List rendering is also supported withof
Replacein
As a delimiter, it is closer to the syntax of JavaScript iterators:
<li v-for="book of books">{{book.name}}</li>
v-for
The expression for supports an optional parameter as the index of the current item.
<li v-for="(book,index) of books">{{index}} - {{book.name}}</li>
Separatorin
Before the statement using parentheses, the second item isbooks
The index of the current item.
Andv-if
Same,v-for
It can also be used in built-in labels.<template>
On, render multiple elements.
In addition to arrays, the properties of objects can also be traversed.
When traversing object properties, there are two optional parameters: key name and index:
<div id="app">
<ul>
<li v-for="(value,key,index) of users">
{{index}} - {{key}} - {{value}}
</li>
</ul>
</div>
v-for
You can also iterate over integers:
<div id="app">
<span v-for="n in 10">{{n}}</span>
</div>
Array update
The core of Vue is the two-way binding of data and views, which includes a set of methods to observe array changes. Using them to change arrays will also trigger view updates:
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
Using the above methods will change the original array called by these methods.
The following methods will not change the original array:
filter()
concat()
slice()
They return a new array, and when using these non-mutating methods, the element group can be replaced by the new array.
When Vue detects an array change, it does not directly re-render the entire list, but reuses DOM elements to the maximum. In the replaced array, items with the same elements will not be re-rendered, so you can boldly replace the old array with the new one without worrying about performance.
It should be noted that in the following changed arrays, Vue cannot be detected and view update will not be triggered:
- Setting items directly by index,
app.books[3]={}
- Modify the array length,
app.books.length=1
To solve the first problem, the same effect can be achieved in two ways. The first is built-in Vue.set
Methods:
Vue.set(app.books, 3, {
name: '《CSS秘密花园》',
author: '无名氏'
});
If you are using componentization in a webpack, Vue is not imported by default, then you can use it.this.$set
.
Another method:app.books.splice(3,1,{})
Filtering and sorting
If you don’t want to change the original array and want to filter or sort through a copy of the array, you can use the calculation property to return the filtered or sorted array.
Methods and Events
@click can call a method name without parentheses()
, if the method has parameters, the native event object will beevent
Incoming.
This design of monitoring events on HTML elements seems to tightly couple DOM and JavaScript, which violates the principle of separation, but in fact it is just the opposite. Because you can know which method is called through HTML, decoupling logic from DOM, which is easy to maintain.
Most importantly, whenviewModel
When destroying, all the event handlers will be destroyed automatically and need not be handled by themselves.
Vue provides a special variable$event
For accessing native DOM events.
<div id="app">
<a href="https://www.apple.com/" @click="handleClick('禁止打开',$event)">打开链接</a>
</div>
Modifier
Vue supports the following modifiers:
.stop
.prevent
.capture
.self
.once
The specific usage is as follows:
Modifier function | Use examples |
---|---|
Prevent click event bubbling | <a @click.stop="handle"></a> |
Submit events no longer reload pages | <form @submit.prevent="handle"></form> |
Modifiers can be concatenated | <a @click.stop.prevent="handle"></a> |
Only modifiers | <form @submit.prevent></form> |
Use event capture mode when adding event listeners | <div @click.capture="handle">...</div> |
Callbacks are only executed when the event triggers on the element itself (not a child element) | <div @click.self="handle">...</div> |
Triggered only once, the component is also applicable. | <div @click.once="handle">...</div> |
You can also use key modifiers when listening for keyboard events on form elements.
Modifier function | Use examples |
---|---|
Only inkeyCode Yes13 Called whenvm.submit()
|
<input @keyup.13="submit"> |
In addition to the specific onekeyCode
In addition, Vue also provides some shortcut names:
.enter
.tab
-
.delete
(Replenishment “Delete” and “Backspace” Keys) .esc
.space
.up
.down
.left
.right
These key modifiers can also be used in combination or with a mouse:
.ctrl
.alt
.shift
.meta