6、v-for
基於源數據多次渲染元素或模板塊。
圖示:
代碼:
<body>
<div id="app">
<p v-for="(score, index) in scores">
索引: {{index }} , 分數: {{score}}
</p>
<div v-for="(d, key) in dog">
{{key + ':' + d}}
</div>
</div>
<script src="js/vue.js"></script>
<script>
// 1. 創建Vue的實例
new Vue({
el: '#app',
data: {
scores: [100, 90, 70, 60, 5], // 數組
dog: {name: 'Python', age: 2, width: 1.44, weight: '100斤'}, // 對象
}
});
</script>
7、v-for小案例
圖示:
代碼:
<body>
<div id="app">
<table>
<thead>
<tr>
<th>姓名</th>
<th>年齡</th>
<th>性別</th>
</tr>
</thead>
<tbody>
<tr v-for="(p, index) in persons">
<td>{{p.name}}</td>
<td>{{p.age}}</td>
<td>{{p.sex}}</td>
</tr>
</tbody>
</table>
</div>
<script src="js/vue.js"></script>
<script>
// 1. 創建Vue的實例
new Vue({
el: '#app',
data: {
persons: [
{name: '張三', age: 18, sex: '男'},
{name: '李四', age: 28, sex: '女'},
{name: '張三', age: 18, sex: '男'},
{name: '王五', age: 38, sex: '女'}
]
}
});
</script>
8、v-bind
v-bind 主要用於屬性綁定
圖示:
代碼:
<body>
<div id="app">
<img v-bind:src="imgSrc" v-bind:alt="alt">
<img :src="imgSrc1" :alt="alt">
</div>
<script src="js/vue.js"></script>
<script>
// 1. 創建Vue的實例
new Vue({
el: '#app',
data: {
imgSrc: 'img/img_01.jpg',
imgSrc1: 'img/img_02.jpg',
alt: '風景'
}
});
</script>
9、v-on
綁定事件監聽器。事件類型由參數指定。表達式可以是一個方法的名字或一個內聯語句,如果沒有修飾符也可以省略。
圖示:
代碼:
<body>
<div id="app">
<p>{{msg}}</p>
<button v-on:click="msg = 'Java'">改變內容</button>
<button @click="msg = 'Vue'">改變內容</button>
<button @click="changeContent()">改變內容</button>
</div>
<script src="js/vue.js"></script>
<script>
// 1. 創建Vue的實例
new Vue({
el: '#app',
data: {
msg: 'Python'
},
methods: {
changeContent() {
this.msg = '編程';
}
}
});
</script>
10、v-model
預期:隨表單控件類型不同而不同。
圖示:
代碼:
<body>
<div id="app">
<h1>{{msg}}</h1>
<input type="text" v-model="msg">
</div>
<script src="js/vue.js"></script>
<script>
// 1. 創建Vue的實例
new Vue({
el: '#app',
data: {
msg: 'hello'
}
});
</script>