Template Syntax Overview
Vue.js uses htMl-based template syntax that allows developers to declaratively bind DOM to the data of the underlying component instance. All vue.js templates are valid HTML, so they can be parsed by standards-compliant browsers and HTML parsers.
On the underlying implementation, Vue compiles templates into virtual DOM rendering functions. Combined with a responsive system, Vue intelligently calculates how many components need to be rerendered and minimizes DOM operations.
If you are familiar with the virtual DOM and prefer the raw power of JavaScript, you can also write the render function without templates, using the optional JSX syntax.
The interpolation
Text (interpolation)
The most common form of data binding is text interpolation using “Mustache” syntax (double braces) :
<span>Message: {{ msg }}</span>
Copy the code
The Mustache tag will be replaced with the value of the MSG property in the corresponding component instance. Whenever the MSG property changes on the bound component instance, the content at the interpolation is updated.
Raw HTML
Double braces do not parse HTML code. To output real HTML, you need to use the V-HTML directive.
<p>Using v-html directive: <span v-html="rawHtml"></span></p>. rawHtml: '<span style="color: red">This should be red.</span>'
Copy the code
Note: Dynamically rendering arbitrary HTML on your site is very dangerous, as it can easily lead to XSS attacks. Use HTML interpolation only for trusted content and never for user-supplied content.
Attribute
(Attribute: Attribute of the element tag)
(Property: property of the element object)
The ustache syntax cannot be used in HTML attributes, however, the V-bind directive can be used:
<div v-bind:id="dynamicId"></div>
Copy the code
If the binding value is null or undefined, the attribute will not be included on the rendered element.
For Boolean attributes (which simply exist means the value is true), V-bind works slightly differently, in this case:
<button v-bind:disabled="isButtonDisabled">button</button>
Copy the code
If the value of isButtonDisabled is truthy, the disabled attribute will be included. If the value is an empty string, it is also included, consistent with
Using JavaScript expressions
Vue.js provides full JavaScript expression support for all data binding
{{ number + 1 }}
{{ ok ? 'YES' : 'NO' }}
{{ message.split('').reverse().join('') }}
<div v-bind:id="'list-' + id"></div>
Copy the code
instruction
Directives are essentially custom properties
Directives are special attributes prefixed with a V -. The value of the directive attribute is expected to be a single JavaScript expression (v-for is the exception, which we’ll discuss later). The directive’s job is to react to the DOM with the collateral effects of changing the value of an expression.
Data binding instruction
v-text
To: fill plain text
Contrast:
- And interpolation expressions {{}} :
V-text overwrites the original contents of the element. Interpolation {{}} replaces only its own placeholder, not the entire contents of the element.
- And v – HTML:
V-text and {{}} expressions render data without parsing labels.
V-html can not only render data, but also parse tags.
Example:
<span v-text="msg"></span>
<! -- equivalent to -->
<span>{{msg}}</span>
Copy the code
v-html
To: fill in HTML fragments, parse tags.
Disadvantages: There are security issues. Dynamically rendering arbitrary HTML on a website is very dangerous because it is prone to XSS attacks. Use V-HTML only for trusted content, never for user-submitted content. This website internal data can be used, data from third parties is not available.
Example:
HTML:
<div v-html="html"></div>
Copy the code
v-pre
To: display the raw information, skip the compilation process.
Example:
HTML:
<span v-pre>{{ this will not be compiled }}</span>{{this will not be compiled}}Copy the code
Two-way data binding
v-model
Restrictions: on ,
Features:
Internally, the V-Model uses different properties for different input elements and throws different events:
- Text and Textarea elements use value property and input events;
- Checkbox and radio use checked Property and change events;
- The SELECT field takes value as prop and change as an event.
Note:
For languages that require input methods (such as Chinese, Japanese, Korean, etc.), you will find that the V-Model is not updated during the input method organization process. If you also want to respond to these updates, use the input event listener and value binding instead of using the V-Model.
Example:
<input v-model="message"/>
Copy the code
MVVM design ideas
Vue.js implements bidirectional data binding through MVVM.
Talk more about Vue learning Notes – MVVM model and MVC model
event
v-on
Abbreviations: @
When used on normal elements, only native DOM events can be listened for. When used on custom element components, it can also listen for custom events triggered by child components.
1.0.11+ When listening for custom events, inline statements have access to a $arguments property, which is an array containing the arguments to the $emit callback passed to the child component.
The basic use
Example:
HTML:
<div id='app'>
<div>{{num}}</div>
<div>
<button v-on:click='num++'>Button 1</button>
<! -- no colon after @! -->
<button @click='num++'>Button 2</button>
<button @click='handle'>Button 3</button>
<button @click='handle()'>Button 3</button>
</div>
</div>
Copy the code
JS:
var vm = new Vue({
el: '#app'.data() {
return {
num: 0}},methods: {
handle: function(){
console.log(this === vm);//true this is the Vue instance object
this.num++; }}})Copy the code
Parameter transfer mode
HTML:
<div id='app'>
<div>{{num}}</div>
<div>
<! To pass the event object, the parameter must be placed last and the name must be $event -->
<button @click='handle1(123, 456, $event)'>Button 1</button>
<button @click='handle2'>Button 2</button>
</div>
</div>
Copy the code
js:
handle1: function(p1, p2, event){// Event is a parameter, not fixed
this.num++;
console.log(p1, p2, event.target);// Get the target} that triggers the event.
handle2: function(event){$event is passed by default when no parameter is passed
this.num++;
console.log(event.target);
},
Copy the code
Conclusion:
- If the event is directly bound to the function name (without parentheses), the event object is passed as the first argument to the function event by default
- If the event binds the function call (bracketed), thenThe event object must be explicitly passed as the last parameterAnd the name of the event object must be
$event
The modifier
1. Stop bubbles
Call event. StopPropagation ()
<! Stop bubbling -->
<button @click.stop="doThis"></button>
Copy the code
2,. Prevent default behavior
Calls to the event. The preventDefault ()
<! -- Block default behavior -->
<button @click.prevent="doThis"></button>
<! -- Block default behavior, no expression -->
<form @submit.prevent></form>
Copy the code
Modifiers can be concatenated:
<! -- modifiers can be concatenated -->
<a v-on:click.stop.prevent="doThat">
Copy the code
3..capture Use capture mode to add event listeners
<div v-on:click.capture="doThis">.</div>
Copy the code
4..self fires the callback only if the event is fired from the listener bound element itself
5. {keyCode | keyAlias} only on the specified key trigger callbacks
<! -- Key modifier, key alias -->
<input @keyup.enter="onEnter">
<! -- Key modifier, key code -->
<input @keyup.13="onEnter">
Copy the code
Attributes bind
v-bind
Abbreviations: :
HTML:
<div id='app'>
<a :href='url'>baidu</a>
</div>
Copy the code
VUE:
data() {
return {
url: 'http://www.baidu.com'}},Copy the code
Style binding
The class binding
CSS:
.active {
border: 1px solid red;
width: 100px;
height: 100px;
}
.error {
background: orange;
}
.base {
font-size: 25px;
}
.text {
color: purple;
}
Copy the code
HTML:
<div id='app'>
<! -- Does not affect default class -->
<div class='base' :class='objClasses'>Obj style, recommended</div>
<div :class='arrClasses'>Arr style, not recommended</div>
<div :class='[activeClass, errorClass, {text: isTest}]'>Object arrays can be used together and are not recommended</div>
</div>
Copy the code
VUE:
data() {
return {
activeClass: 'active'.errorClass: 'error'.isTest: true.arrClasses: [
'active'.'error'].objClasses: {
active: true.error: true}}},Copy the code
Style binding
HTML:
<div id='app'>
<div :style='objStyles'>object</div>
<div :style='[objStyles, overrideStyles]'>An array of</div>
<button @click='handle'>Switch the style</button>
</div>
Copy the code
VUE:
data() {
return {
objStyles: {
border: '1px solid blue'.width: '200px'.height: '200px'
},
overrideStyles: {
border: '5px solid orange'.backgroundColor: 'blue'}}},methods: {
handle: function(){
this.objStyles.height = '400px'}},Copy the code
Conditions apply colours to a drawing
V-if, V-else -if, V-else
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 truthy.
<h1 v-if="awesome">Vue is awesome!</h1>
Copy the code
It is recommended to use v-if conditional rendering groups in
elements:
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.
You can also use v-else if, v-else
Manage reusable elements with keys
For example, the user switches between different login methods:
<template v-if="loginType === 'username'">
<label>Username</label>
<input placeholder="Enter your username">
</template>
<template v-else>
<label>Email</label>
<input placeholder="Enter your email address">
</template>
Copy the code
Switching loginType in the code above will not clear what the user has entered. Because both templates use the same element, the will not be replaced — just its placeholder.
So if you enter text in the input field, and then switch, the text in the input field is still there.
If you don’t need to reuse an element, you can add a key attribute with a unique value to the element:
<template v-if="loginType === 'username'">
<label>Username</label>
<input placeholder="Enter your username" key="username-input">
</template>
<template v-else>
<label>Email</label>
<input placeholder="Enter your email address" key="email-input"> </template>
Copy the code
Note that
v-show
Note:
V-show elements are always rendered and retained in the DOM. V-show simply toggles the element’s CSS property display
V-show is different from V-if
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 lazy: if the condition is false during the 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.
It is not recommended to use v-IF and V-for at the same time. V-for has a higher priority than V-if
To iterate over
Through the array
<li :key='index' v-for='(item, index) in fruits'>{{item + '---' +index}}</li>
Copy the code
Key: Helps Vue differentiate between different elements to improve performance.
Traverse object
<li v-for='(key, value) in objs'>{{key + "---" + value}}</li>
Copy the code
Data response
How to Understand:
- Responsive in HTML: Changes in screen size result in changes in style.
- Responsiveness of data: Changes in data result in changes in page content.
Data binding: Data is populated into a TAB.
v-once
In order to: compile only once, display content no longer have responsivity. If the displayed content does not need to be changed, v-once can be used to improve performance.
Example:
<div v-once>{{info}}</div>
Copy the code
Other instructions
v-cloak
To solve the flash problem of interpolation expressions
Principle: hide first, replace the value and then display
This directive remains on the element until the associated component instance is finished compiling. Used with CSS rules such as [V-cloak] {display: None}, this instruction can hide the uncompiled Mustache tag until the component instance is ready.
Example:
css:
[v-cloak] {
display: none;
}
Copy the code
HTML:
<div v-cloak>
{{ message }}
</div>
Copy the code
To be continued (incomplete && modifier)…