Data and Methods
- When a Vue instance is created, all properties it is added to the data object in response to the systems Vue. data synchronization update data and views.
- Add a new property after the instance is created, changes to this attribute will not be updated any view.
- If you desired a property, but it was the beginning of an empty or not present, only a few need to set initial values.
- Object.freeze () method prevents modify existing properties
- In addition to data attributes, further comprising Vue instance instance attributes and methods , as a prefix
$
, for example:. Vm $ data, vm $ el, vm $ watch () ( vm is assumed here that a specific instance name), details refer to.. The API
Examples of lifecycle hook
Vue instance has its own life cycle, provides some hook function to write our own logic code:
- beforeCreate
- created
- beforeMount
- mounted
- beforeUpdate
- updated
ps: 不要在选项属性或回调上使用箭头函数,即这些钩子函数不要用箭头函数的写法,因为他们没有this
Lifecycle chart
Template syntax
Text
data binding is the most common form of the use of“Mustache”
grammar (curly brackets) Text Interpolation<span>Message: {{ msg }}</span>
v-once instruction, you can perform a one-time interpolation, when the data changes, the content of the interpolation is not updated at
<span v-once>这个将不会改变: {{ msg }}</span>
Original the HTML
V-real HTML command output html, rather than a string<p>Using mustaches: {{ rawHtml }}</p> 输出字符串 <p>Using v-html directive: <span v-html="rawHtml"></span></p> 输出rawHtml变量代表的HTML
Use JavaScript expressions
all the data binding, Vue.js provides full support JavaScript expression{{ number + 1 }} {{ ok ? 'YES' : 'NO' }} {{ message.split('').reverse().join('') }} <div v-bind:id="'list-' + id"></div>
Instruction
common with v-if, v-on, v-bind, v-for.
parameter:<a v-bind:href="url">...</a>
Href here is a parameter, the command informing v-bind value of the expression href url characteristic element binding
dynamic parameters:<a v-bind:[attributeName]="url"> ... </a>
AttributeName here will be dynamic as a JavaScript expression is evaluated, the value obtained will be used as the final argument
modifiers:<form v-on:submit.prevent="onSubmit">...</form>
Modifier (modifier) is specified periods to special suffix used to indicate a binding instruction should be in a special way, an example of.
.prevent
Is the modifier
abbreviations:<!-- 完整语法 --> <a v-bind:href="url">...</a> <!-- 缩写 --> <a :href="url">...</a> <!-- 完整语法 --> <a v-on:click="doSomething">...</a> <!-- 缩写 --> <a @click="doSomething">...</a>
And the listener properties calculation
Do not add too much general template logic, will be accountable only to render some of the logic processing computing security attributes, it will be more reasonable;
<p>Computed reversed message: "{{ reversedMessage }}"</p>
var vm = new Vue({
el: '#example',
data: {
message: 'Hello'
},
computed: {
// 计算属性的 getter
reversedMessage: function () {
// `this` 指向 vm 实例
return this.message.split('').reverse().join('')
}
}
})
Here reversedMessage
is calculated the properties and to be a string in reverse order.
Define a method, the same effect can be achieved:
<p>Reversed message: "{{ reversedMessage() }}"</p>
<p>
// 在组件中
methods: {
reversedMessage: function () {
return this.message.split('').reverse().join('')
}
}
Difference between the two: Calculation is based on their property responsive dependent caching process always executes function again; choose different ways in different scenarios it ~
Tips: using the calculated property, rather than the listener properties (defined in Watch method); calculate the default attribute only getter, but if necessary you can also provide a setter; custom listeners watch perform asynchronous data changes or when the cost of a larger operation is most useful
Class and Style Bind
v-bind to class type and style, in addition to the results of the expression 字符串
, but also may be 对象
or 数组
introduce binding Class
Bound object
<div class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }"> </div> data: { isActive: true, hasError: false }
When isActive or hasError change, class lists will be updated accordingly, can not make binding object defined inline in a template, the result is the same:
Binding<div v-bind:class="classObject"></div> data: { classObject: { active: true, 'text-danger': false } }
计算属性
can be more flexible to show (not a child, for example)Bind array
<div v-bind:class="[activeClass, errorClass]"></div> data: { activeClass: 'active', errorClass: 'text-danger' }
Binding component (grammar and front completely analogous)
Style bindings
v-bind: style object syntax
Bound object
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div> data: { activeColor: 'red', fontSize: 30 }
Or write directly
<div v-bind:style="styleObject"></div> data: { styleObject: { color: 'red', fontSize: '13px' } }
Bind array
<div v-bind:style="[baseStyles, overridingStyles]"></div>
Conditions rendering
v-if, v-else-if, v-else can be used with:
<div v-if="type == 'A'">
A
</div>
<div v-else-if="type == 'B'">
B
</div>
<div v-else="type == 'C'">
C
</div>
data : {
type : "B"
}
In <template>
using the v-if conditions render elements grouped plurality of display elements
<template v-if="ok">
<h1>Title</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</template>
Repeat with key management elements
<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>
After using key labeling elements, Vue will not use lazy reuse, and re-render elements
v-show: not only display and show two
<h1 v-show="ok">Hello!</h1>
v-if vs v-show: the need to switch very frequently, use the v-show better; if conditions rarely change at runtime, use the v-if better
Rendering list
v-for rendering a list of
Iterative array
ps: index starts from 0,<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' } ] } })
in
may be replacedof
Iterables
<div v-for="(value, name, index) in object"> {{ index }}. {{ name }}: {{ value }} </div>
new Vue({ el: '#v-for-object', data: { object: { title: 'How to do lists in Vue', author: 'Jane Doe', publishedAt: '2016-04-10' } } })
Use a unique key with the v-for to ensure correct rendering (delete, sort, filter, and other scenes used to get)
<div v-for="item in items" v-bind:key="item.id"> <!-- 内容 --> </div>
Array mutation method (Method mutation)
Push (), POP (), Shift (), the unshift (), splice (), Sort (), Reverse (), examples:
These methods will directly change the array itselfexample1.items.push({ message: 'Baz' })
Non-variant (non-mutating method) Method
filter (), concat (), slice ()
These methods do not change passed array itself, but the methodexample1.items = example1.items.filter(function (item) { return item.message.match(/Foo/) })
返回值
is a新数组
, this array can be assigned to the original array to achieve the same effect
Notes
array of some errors wording:var vm = new Vue({ data: { items: ['a', 'b', 'c'] } }) vm.items[1] = 'x' // 不是响应性的 vm.items.length = 2 // 不是响应性的
Correct wording:
//第一个问题 // Vue.set Vue.set(vm.items, indexOfItem, newValue) // Array.prototype.splice vm.items.splice(indexOfItem, 1, newValue) //实例写法 vm.$set(vm.items, indexOfItem, newValue) //第二个问题 vm.items.splice(newLength)
Some errors wording object:
var vm = new Vue({ data: { a: 1 } }) // `vm.a` 现在是响应式的 vm.b = 2 // `vm.b` 不是响应式的
For the example has been created, not allowed to dynamically add Vue
根级别
responsive properties, however, may be used Vue.set (object, propertyName, value) method was added to the nested object responsive properties:var vm = new Vue({ data: { userProfile: { name: 'Anika' } } }) Vue.set(vm.userProfile, 'age', 27) //或者 vm.$set(vm.userProfile, 'age', 27)
Binding form input
v-model command in the form <input>
, <textarea>
and <select>
create two-way data binding on elements of syntactic sugar in nature.
text
<input v-model="message" placeholder="edit me"> <p>Message is: {{ message }}</p>
Multiple lines of text
Tips: (<span>Multiline message is:</span> <p style="white-space: pre-line;">{{ message }}</p> <br> <textarea v-model="message" placeholder="add multiple lines"></textarea>
<textarea>{{text}}</textarea>
) does not take effect, use v-model instead.Box
plurality of checkboxes, bound to the same array, example:<div id='example-3'> <input type="checkbox" id="jack" value="Jack" v-model="checkedNames"> <label for="jack">Jack</label> <input type="checkbox" id="john" value="John" v-model="checkedNames"> <label for="john">John</label> <input type="checkbox" id="mike" value="Mike" v-model="checkedNames"> <label for="mike">Mike</label> <br> <span>Checked names: {{ checkedNames }}</span> </div>
new Vue({ el: '#example-3', data: { checkedNames: ['Jack'] } })
single button
<div id="example-4"> <input type="radio" id="one" value="One" v-model="picked"> <label for="one">One</label> <br> <input type="radio" id="two" value="Two" v-model="picked"> <label for="two">Two</label> <br> <span>Picked: {{ picked }}</span> </div>
new Vue({ el: '#example-4', data: { picked: 'Two' } })
Select box
Radio:<div id="example-5"> <select v-model="selected"> <option disabled value="">请选择</option> <option>A</option> <option>B</option> <option>C</option> </select> <span>Selected: {{ selected }}</span> </div>
new Vue({ el: '...', data: { selected: 'A' } })
When multiple choice (to bind an array):
<div id="example-6"> <select v-model="selected" multiple style="width: 50px;"> <option>A</option> <option>B</option> <option>C</option> </select> <br> <span>Selected: {{ selected }}</span> </div>
new Vue({ el: '#example-6', data: { selected: ['A','B'] } })
v-for example, a drop-down box:
<select v-model="selected"> <option v-for="option in options" v-bind:value="option.value"> {{ option.text }} </option> </select> <span>Selected: {{ selected }}</span>
new Vue({ el: '...', data: { selected: 'A', options: [ { text: 'One', value: 'A' }, { text: 'Two', value: 'B' }, { text: 'Three', value: 'C' } ] } })
- The bind
option radio buttons, check boxes and selection boxes, the value of v-model binding generally static strings, sometimes we may want to bind the value to a dynamic property Vue instance, then you can use v-bind achieved, and the value of this property can not string (for example a child) - Modifiers
- .lazy
By default, v-model synchronized with the data in the value of each input event will trigger input box, you can add a modifier lazy, so use change into a synchronized event
<!-- 在“change”时而非“input”时更新 --> <input v-model.lazy="msg" >
- .number
If the user wants to automatically input value into a numeric type, number modifier may be added to the v-model
<input v-model.number="age" type="number">
- .trim
To automatically filtered inclusive whitespace characters input by a user, the modifier may be added to trim v-model:
<input v-model.trim="msg">
- .lazy