class
# object syntaxWe can pass :class an object to dynamically toggle class: <div v-bind:class="{ active: isActive }"></div>
<div class="static"
v-bind:class="{ active: isActive, 'text-danger': hasError }"> </div> and the following data: data: {isActive:true,
hasError: false} bound data objects need not be defined inline in the template: <div :class="classObject"></div>
data: {
classObject: {
active: true.'text-danger': false}}It is also possible to bind a computed property of the returned object here. This is a common and powerful pattern:
<div v-bind:class="classObject"></div>
data: {
isActive: true,
error: null
},
computed: {
classObject: function () {
return{ active: this.isActive && ! this.error,'text-danger': this.error && this.error.type === 'fatal'}}}Array syntax passes an array to :class
<div v-bind:class="[activeClass, errorClass]"></div>
data: {
activeClass: 'active',
errorClass: 'text-danger'} Render to: <div class="active text-danger"></div>
Toggle the class in the list with a ternary expression based on the condition:
<div v-bind:class="[isActive ? activeClass : '', errorClass]"></div>
We can use array syntax as well as object syntax for multiple conditional classes:
<div v-bind:class="[{ active: isActive }, errorClass]"></div> When the class attribute is used on a custom component, these classes are added to the root element of that component. Classes that already exist on this element are not overwritten. Vue.component('my-component', {
template: '<p class="foo bar">Hi</p>'}) then add some classes when you use it: <my-component class="baz boo"></my-component> HTML will be rendered as: <p class="foo bar baz boo">Hi</p>
Copy the code
style
# object syntaxThe object syntax for :style is a JavaScript object. CSS attribute names can be camelCase or kebab-case delimited: <div V-bind :style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>
data: {
activeColor: 'red', fontSize: 30} It is usually better to bind directly to a style object, which makes the template clearer: <div V-bind :style="styleObject"></div>
data: {
styleObject: {
color: 'red',
fontSize: '13px'}} Object syntax is often used in conjunction with computed properties that return objects.# array syntaxThe array syntax for :style can apply multiple style objects to the same element: <div V-bind :style="[baseStyles, overridingStyles]"></div>
# Add prefixes automaticallyWhen :style uses CSS attributes that need to be prefixed by the browser engine, such as transform, vue.js will automatically detect and add the corresponding prefix.Since you can provide an array of multiple values for a property in the style binding, this is often used to provide multiple prefixed values, for example:
<div :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"></div> this will render only the last value in the array that is supported by the browser. In this case, if the browser supports flexbox without the browser prefix, only display: flex will be rendered.Copy the code
v-if
<h1 v-if="ok">Yes</h1> <h1 V-else >No</h1> How about switching multiple elements on <template> elements using V-if conditional rendering groups? You can treat a <template> element as an invisible wrap element and use v-if on it. <template v-if="ok">
<h1>Title</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</template>
v-else
Copy the code
The V-else instruction represents the “else block” of v-if:
The V-else element must be immediately followed by an element with v-if or v-else-if, otherwise it will not be recognized.Copy the code
V – else – the if (2.1.0 new) :
Act as a V-if.else-if block ", can be used consecutively: <div v-if="type === 'A'">
A
</div>
<div v-else-if="type === 'B'">
B
</div>
<div v-else-if="type === 'C'">
C
</div>
<div v-else>
Not A/B/C
</div>
Copy the code
Manage reusable elements with keys
Elements are rendered as efficiently as possible, often reusing existing elements rather than rendering from scratch. This has other benefits besides making Vue very fast. For example, if you allow users to switch 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> Then switching loginType in the code above will not clear what the user has entered. Because both templates use the same element, the <input> will not be replaced -- just its placeholder. Use the key ='Unique value'To say "These two elements are completely independent, don't reuse them." <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
v-show
<h1 v-show="ok">Hello! </h1> Elements with a V-show are always rendered and retained in the DOM. V-show simply toggles the element's CSS attribute display. V-show does not support <template> elements, nor does v-else. V-if: Switching overhead is high, while v-show initial rendering overhead is high. Therefore, if you switch frequently, v-show is better; Run time conditions rarely change, so v-if is preferable.Copy the code
List render V-for
# v - for the arrayThe V-for instruction renders from an array of options. The V-for directive needs to use iteminSpecial syntax for items, where items is the source data array and item is an alias for an iteration of an array element. <ul id="example-1">
<li v-for="item in items">
{{ item.message }}
</li>
</ul>
var example1 = new Vue({
el: '#example-1',
data: {
items: [
{ message: 'Foo' },
{ message: 'Bar'}]}}) the second argument is the index of the current item. <ul id="example-2">
<li v-for="(item, index) in items">
{{ parentMessage }} - {{ index }} - {{ item.message }}
</li>
</ul>
var example2 = new Vue({
el: '#example-2',
data: {
parentMessage: 'Parent',
items: [
{ message: 'Foo' },
{ message: 'Bar'}]}}) You can also use of insteadinAs a separator, because it is the syntax closest to a JavaScript iterator: <div v-for="item of items"></div>
# v - for objects
<ul id="v-for-object" class="demo">
<li v-for="value in object">
{{ value }}
</li>
</ul>
new Vue({
el: '#v-for-object',
data: {
object: {
firstName: 'John',
lastName: 'Doe', age: 30}}}) <div v-for="(value, key) in object"> {{key}}, {{value}} < / div > (2) the third argument for the index: < div v - for ="(value, key, index) in object"> {{index}}. {{key}}: {{value}} </div> When traversing an Object, it follows the result of object.keys (), but there is no guarantee that its result will be consistent across different JavaScript engines.# :keySo that it can track the identity of each node, reusing and reordering existing elements, :key The ideal key value is a unique ID that each item has. <div v-for="item in items" :key="item.id"> <! It is recommended to provide keys whenever possible with V-for, unless traversing the output DOM content is very simple or you deliberately rely on default behavior for performance gains.Array update detectionVue contains a set of mutating methods that observe arrays, so they will also trigger view updates: push() POP ()shift() unshift() splice() sort() reverse() You open the console and call the mutant method example1.items.push({message:'Baz'}).Display filter/sort resultsSometimes we want to display a filtered or sorted copy of an array without actually changing or resetting the original data. In this case, you can create computed properties that return filtered or sorted arrays. In cases where computed attributes do not apply (for example, in nested V-for loops) you can use a method method: <li v-for="n in even(numbers)">{{ n }}</li>
data: {
numbers: [ 1, 2, 3, 4, 5 ]
},
methods: {
even: function (numbers) {
return numbers.filter(function (number) {
return number % 2 === 0
})
}
}
# V -for for a range of valuesV minus for can also be integers. In this case, it will repeat the template multiple times. <div> <span v-for="n in 10">{{ n }} </span>
</div>
# v-for on a <template>Similar to v-if, you can render multiple elements with <template> with v-for. For example: <ul> <template v-for="item in items">
<li>{{ item.msg }}</li>
<li class="divider"></li>
</template>
</ul>
# v-for & v-ifThe same node, v-for has a higher priority than V-IF, which means that V-IF will run separately in each V-for loop. This priority mechanism is useful when you want to render nodes for only a few items, <li v-for="todo in todos" v-if=! "" todo.isComplete"> {{todo}} </li> The code above passes only unfinished TODOS.To conditionally skip the loop, place v-if on the outer element (or
). Such as:
<ul v-if="todos.length">
<li v-for="todo in todos"> {{ todo }} </li> </ul> <p v-else>No todos left! </p># A component of v-for
<my-component v-for="item in items" :key="item.id"></my-component> Components have their own independent scope. To pass iteration data to the component, we want to use props: <my-component v-for="(item, index) in items"
:item="item"
:index="index"
:key="item.id"/> The reason for not automatically injecting item into the component is that it tightly couples the component to the v-for operation. Knowing where component data comes from enables components to be reused in other contexts. <div id="todo-list-example">
<input
v-model="newTodoText"
v-on:keyup.enter="addNewTodo"
placeholder="Add a todo"
>
<ul>
<li
is="todo-item"
v-for="(todo, index) in todos"
:key="todo.id"
:title="todo.title"
@remove="todos.splice(index, 1)"/> </ul> </div> Notice is="todo-item"Properties. This is necessary when using DOM templates, because only <li> elements are considered valid within <ul> elements. Doing so achieves the same effect as <todo-item>, but avoids some potential browser parsing errors.Copy the code