Vue 101-Day 3
27 Apr 2019 |接下來就要講解 Vue 相關使用語法
Declarative Rendering
Vue 可以使用宣告式的方法將資料渲染到 DOM
首先先在 component 資料夾底下新增一個名為 HelloVue 的 component
<div id="app-3">
{{ info }}
</div>
new Vue({
el: '#app-3',
data: {
info: 'Hi~~'
}
});
要記得在 index.js 引用 component
除了interpolation(插值)
,也可以綁定元素屬性(bind element attribute)
<div id="app-3">
<span v-bind:style="{color : color}">bind color</span>
</div>
template 所看到的 v-bind 就是 directive,
在 Vue 裡面,所有v-開頭的屬性,就是Vue所提供的directive
Conditionals and Loops
v-if
利用條件決定是否顯示
<div id="app-3">
<span v-if="seen">Now you see me.</span>
</div>
new Vue({
el: '#app-3',
data: {
seen: true
}
});
seen 若設為 false,畫面上就不會顯示 span 這個 tag
v-for
可以將顯示的資料存進 Array,接著使用 v-for iteration 裡面的結果。
<div id="app-3">
<li v-for="todo in todos" v-bind:key="todo"></li>
</div>
new Vue({
el: '#app-3',
data: {
todos: [{ message: 'Foo' }, { message: 'Bar' }]
}
});
註:v-bind:key 必須與 v-for 一起使用
,以下為官方說明
In 2.2.0+, when using v-for with a component, a key is now required.
Handling User Input
要和使用者互動,就可以使用v-on
這個 directive,它可以綁定所指定的 event
<div id="app-3">
<p>{{ info }}</p>
<button v-on:click="reverseInfo">Reverse Info</button>
</div>
new Vue({
el: '#app-3',
data: {
info: 'Hello Vue.js!'
},
methods: {
reverseInfo: function() {
this.info = this.info
.split('')
.reverse()
.join('');
}
}
});
two-way binding
使用v-model
進行雙向綁定,以下面範例來說:input 的值會隨著使用者的輸入,而動態調整
<div id="app-3">
<p>{{ info }}</p>
<input v-model="info" />
</div>
new Vue({
el: '#app-3',
data: {
info: 'Hello Vue.js!'
}
});
Component
Component 對於寫過 Angular 的人應該不陌生,使用 Component 其中一個好處就是可以重複使用
語法為:Vue.component('component-name', 'options')
<div id="app-3">
<todo-item></todo-item>
</div>
Vue.component('todo-item', {
template: '<li>This is a todo</li>'
});
new Vue({
el: '#app-3'
});
props
props 為 component 裡自定義的屬性,可以用v-bind:prop-name
做綁定
<div id="app-3">
<todo-item
v-for="item in groceryList"
v-bind:todo="item"
v-bind:key="item.id"
></todo-item>
</div>
Vue.component('todo-item', {
props: ['todo'],
template: '<li>{{ todo.text }}</li>'
});
new Vue({
el: '#app-3',
data: {
groceryList: [
{ id: 0, text: 'Vegetables' },
{ id: 1, text: 'Cheese' },
{ id: 2, text: 'Whatever else humans are supposed to eat' }
]
}
})
參考資料:
Comments