1. v-bind abbreviation
<!-- Complete syntax--><a v-bind:href="url"></a><!-- Abbreviation--><a :href="url"></a><!-- Complete syntax--><button v-bind:disabled="someDynamicCondition">Button</button><!-- Abbreviation--><button :disabled="someDynamicCondition">Button</button>
2. v-on abbreviation
<!-- Complete syntax--><a v-on:click="doSomething"></a><!-- Abbreviation--><a @click="doSomething"></a>
3. Filter
{{ message | capitalize }}4. Conditional Rendering
v-if<h1 v-if="ok">Yes</h1><h1 v-else>No</h1><div v-if="Math.random() > 0.5"> Sorry</div><div v-else> Not sorry</div>template-v-if<template v-if="ok"> <h1>Title</h1> <p>Paragraph 1</p> <p>Paragraph 2</p></template>v-show<h1 v-show="ok">Hello!</h1>
5. List rendering for
v-for<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' } ] }}); <ul id="example-2"> <li v-for="item in items"> {{ parentMessage }} - {{ $index }} - {{ item.message }} </li></ul>var example2 = new Vue({ el: '#example-2', data: { parentMessage: 'Parent', items: [ { message: 'Foo' }, { message: 'Bar' } ] }});Array change detection
Vue.js wraps the mutated methods of the observed arrays, so they can trigger view updates. The methods wrapped are: push(), pop(), shift(), unshift(), splice(), sort(), reverse()
example1.items.push({ message: 'Baz' });example1.items = example1.items.filter(function (item) { return item.message.match(/Foo/);}); template-v-for<ul> <template v-for="item in items"> <li>{{ item.msg }}</li> <li></li> </template></ul>Object v-for
<ul id="repeat-object"> <li v-for="value in object"> {{ $key }} : {{ value }} </li></ul>new Vue({ el: '#repeat-object', data: { object: { FirstName: 'John', LastName: 'Doe', Age: 30 } }});Value range v-for
<div> <span v-for="n in 10">{{ n }} </span></div>6. Methods and event handlers
Method Processor
<div id="example"> <button v-on:click="greet">Greet</button></div>var vm = new Vue({ el: '#example', data: { name: 'Vue.js' }, // Define methods in the `methods` object: { greet: function (event) { // In the method `this` points to vm alert('Hello ' + this.name + '!') // `event` is a native DOM event alert(event.target.tagName) } }})// You can also call the method vm.greet() in JavaScript code; // -> 'Hello Vue.js!'Inline statement processor
<div id="example-2"> <button v-on:click="say('hi')">Say Hi</button> <button v-on:click="say('what')">Say What</button></div>new Vue({ el: '#example-2', methods: { say: function (msg) { alert(msg) } }});Sometimes it is also necessary to access native DOM events in the inline statement processor. You can use the special variable $event to pass it into the method
<button v-on:click="say('hello!', $event)">Submit</button> methods: { say: function (msg, event) { // Now we can access the native event object event.preventDefault() }};## Event Modifier
<!-- Prevent the click event from bubbled --><a v-on:click.stop="doThis"></a><!-- Submit event no longer overloads the page --><form v-on:submit.prevent="onSubmit"></form><!-- Modifiers can be concatenated --><a v-on:click.stop.prevent="doThat"><!-- Only modifiers --><form v-on:submit.prevent></form>
## Key modifier
<!-- vm.submit() is called only when keyCode is 13 --><input v-on:keyup.13="submit"><!-- Same as above-><input v-on:keyup.enter="submit"><!-- Abbreviation Syntax-><input @keyup.enter="submit">
All key alias: enter, tab, delete, esc, space, up, down, left, right
## Other examples
new Vue({ el: '#demo', data: { newLabel: '', stats: stats }, methods: { add: function (e) { e.preventDefault() if (!this.newLabel) { return; } this.stats.push({ label: this.newLabel, value: 100 }); this.newLabel = ''; }, remove: function (stat) { if (this.stats.length > 3) { this.stats.$remove(stat); // Note $remove here } else { alert('Can/'t delete more!') } } }});7. Transition
CSS Transition
<div v-if="show" transition="expand">hello</div> Then add CSS rules for .expand-transition, .expand-enter, and .expand-leave:/* Required*/.expand-transition { transition: all .3s ease; height: 30px; padding: 10px; background-color: #eee; overflow: hidden;}/* .expand-enter Define the start state of entry*//* .expand-leave Define the end state of departure*/.expand-enter, .expand-leave { height: 0; padding: 0 10px; opacity: 0;}You can achieve different transitions on the same element through dynamic binding:
<div v-if="show" :transition="transitionName">hello</div> new Vue({ el: '...', data: { show: false, transitionName: 'fade' }}Additionally, JavaScript hooks can be provided:
Vue.transition('expand', { beforeEnter: function (el) { el.textContent = 'beforeEnter' }, enter: function (el) { el.textContent = 'enter' }, afterEnter: function (el) { el.textContent = 'afterEnter' }, enterCancelled: function (el) { // handle cancellation }, beforeLeave: function (el) { el.textContent = 'beforeLeave' }, leave: function (el) { el.textContent = 'leave' }, afterLeave: function (el) { el.textContent = 'afterLeave' }, leaveCancelled: function (el) { // handle cancellation }});8. Components
1. Register
// Define var MyComponent = Vue.extend({ template: '<div>A custom component!</div>'});// Register Vue.component('my-component', MyComponent);// Create root instance new Vue({ el: '#example'});<div id="example"> <my-component></my-component></div> or write directly as: Vue.component('my-component', { template: '<div>A custom component!</div>'}); // Create root instance new Vue({ el: '#example'});<div id="example"> <my-component></my-component></div>2. Use prop to pass data
Example 1:
Vue.component('child', { // Declare props props: ['msg'], // prop can be used in templates// You can use `this.msg` to set template: '<span>{{ msg }}</span>'});<child msg="hello!"></child>Example 2:
Vue.component('child', { // camelCase in JavaScript props: ['myMessage'], template: '<span>{{ myMessage }}</span>' }); <!-- kebab-case in HTML --> <child my-message="hello!"></child>3. Dynamic props
<div> <input v-model="parentMsg"> <br> <child v-bind:my-message="parentMsg"></child></div>
Using the abbreviation syntax of v-bind is usually simpler:
<child :my-message="parentMsg"></child>
4.Prop binding type
prop is one-way binding by default: when the properties of the parent component change, it will be passed to the child component, but the other way around will not. This is to prevent the child component from accidentally modifying the state of the parent component - this will make the application's data flow difficult to understand. However, it is also possible to explicitly force bidirectional or single-time binding using the .sync or .once binding modifier:
Comparative syntax:
<!-- Default is one-way binding--><child :msg="parentMsg"></child><!-- Bidirectional binding--><child :msg.sync="parentMsg"></child><!-- Single binding--><child :msg.once="parentMsg"></child>Other examples: <modal :show.sync="showModal"> <h3 slot="header">custom header</h3> </modal></div>
5.Prop Verification
Components can specify verification requirements for props. This is useful when components are given to others, because these verification requirements form the component's API, ensuring that others use the component correctly. At this time, the value of props is an object that contains verification requirements:
Vue.component('example', { props: { // Basic type detection (`null` means any type is OK) propA: Number, // Required and string propB: { type: String, required: true }, // Number, with default value propC: { type: Number, default: 100 }, // The default value of an object/array should be returned by a function to propD: { type: Object, default: function () { return { msg: 'hello' } } }, // Specify this prop as a two-way binding// If the binding type is not correct, a warning will be thrown propE: { twoWay: true }, // Custom validation function propF: { validator: function (value) { return value > 10 } }, // Convert the value (new in 1.0.12) // Convert the value before setting the value propG: { coerce: function (val) { return val + '' // Convert the value to a string} }, propH: { coerce: function (val) { return JSON.parse(val) // Convert the JSON string to an object} } } }});Other examples:
Vue.component('modal', { template: '#modal-template', props: { show: { type: Boolean, required: true, twoWay: true } }});6. Register
// Define var MyComponent = Vue.extend({ template: '<div>A custom component!</div>'});// Register Vue.component('my-component', MyComponent);// Create root instance new Vue({ el: '#example'});<div id="example"> <my-component></my-component></div>Or write it directly:
Vue.component('my-component', { template: '<div>A custom component!</div>'}); // Create root instance new Vue({ el: '#example'});<div id="example"> <my-component></my-component></div>7. Use prop to pass data
Example 1:
Vue.component('child', { // Declare props props: ['msg'], // prop can be used in templates// You can use `this.msg` to set template: '<span>{{ msg }}</span>'});<child msg="hello!"></child>Example 2:
Vue.component('child', { // camelCase in JavaScript props: ['myMessage'], template: '<span>{{ myMessage }}</span>' }); <!-- kebab-case in HTML --> <child my-message="hello!"></child>8. Dynamic props
<div> <input v-model="parentMsg"> <br> <child v-bind:my-message="parentMsg"></child></div>
Using the abbreviation syntax of v-bind is usually simpler:
<child :my-message="parentMsg"></child>
9.Prop binding type
prop is one-way binding by default: when the properties of the parent component change, it will be passed to the child component, but the other way around will not. This is to prevent the child component from accidentally modifying the state of the parent component - this will make the application's data flow difficult to understand. However, it is also possible to explicitly force bidirectional or single-time binding using the .sync or .once binding modifier:
Comparative syntax:
<!-- Default is one-way binding--><child :msg="parentMsg"></child><!-- Bidirectional binding--><child :msg.sync="parentMsg"></child><!-- Single binding--><child :msg.once="parentMsg"></child>
Other examples:
<modal :show.sync="showModal"> <h3 slot="header">custom header</h3> </modal></div>
10.Prop Verification
Components can specify verification requirements for props. This is useful when components are given to others, because these verification requirements form the component's API, ensuring that others use the component correctly. At this time, the value of props is an object that contains verification requirements:
Vue.component('example', { props: { // Basic type detection (`null` means any type is OK) propA: Number, // Required and string propB: { type: String, required: true }, // Number, with default value propC: { type: Number, default: 100 }, // The default value of an object/array should be returned by a function to propD: { type: Object, default: function () { return { msg: 'hello' } } }, // Specify this prop as a two-way binding// If the binding type is not correct, a warning will be thrown propE: { twoWay: true }, // Custom validation function propF: { validator: function (value) { return value > 10 } }, // Convert the value (new in 1.0.12) // Convert the value before setting the value propG: { coerce: function (val) { return val + '' // Convert the value to a string} }, propH: { coerce: function (val) { return JSON.parse(val) // Convert the JSON string to an object} } } }});Other examples:
Vue.component('modal', { template: '#modal-template', props: { show: { type: Boolean, required: true, twoWay: true } }});11. Use slot to distribute content
The <slot> element is used as a content distribution slot in the component template. This element itself will be replaced.
A slot with the name attribute is called a named slot. Content with slot attribute will be distributed to named slots with matching names.
For example, suppose we have a multi-insertion component with a template like:
<div> <slot name="one"></slot> <slot></slot> <slot name="two"></slot></div>
Parent component template:
<multi-insertion> <p slot="one">One</p> <p slot="two">Two</p> <p>Default A</p></multi-insertion>
The rendering result is:
<div> <p slot="one">One</p> <p>Default A</p> <p slot="two">Two</p></div>