1. 程式人生 > >Vue.js入門簡單小例子

Vue.js入門簡單小例子

因原文中的Vue.js版本與現在較新的版本語法有些許不同,我只是將原文的程式碼稍作改動,符合2.2.2及以上版本的語法,在此記錄方便自己回顧溫習。

廢話不多說,直接上程式碼:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>vue</title>
	</head>
	<script type="text/javascript" src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
	<body>
		<div id="app">
            <div class="form-group">
                <label>Name:</label>
                <input type="text" v-model="newPerson.name"/>
            </div>
            <div class="form-group">
                <label>Age:</label>
                <input type="text" v-model="newPerson.age"/>
            </div>
            <div class="form-group">
                <label>Sex:</label>
                <select v-model="newPerson.sex">
	                <option value="Male">Male</option>
	                <option value="Female">Female</option>
            	</select>
            </div>
            <div class="form-group">
                <label></label>
                <button @click="createPerson">Create</button>
            </div>
            <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                    <th>Sex</th>
                    <th>Delete</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(person,index) in people">
                    <td>{{ person.name }}</td>
                    <td>{{ person.age }}</td>
                    <td>{{ person.sex }}</td>
                    <td :class="'text-center'"><button @click="deletePerson(index)">Delete</button></td>
                </tr>
            </tbody>
        	</table>
        </div>
	<script>
		var vm = new Vue({
		  el: '#app',
		  data: {
		     newPerson: {
                    name: '',
                    age: 0,
                    sex: 'Male'
                },
                people: [{
                    name: 'Jack',
                    age: 30,
                    sex: 'Male'
                }, {
                    name: 'Bill',
                    age: 26,
                    sex: 'Male'
                }, {
                    name: 'Tracy',
                    age: 22,
                    sex: 'Female'
                }, {
                    name: 'Chris',
                    age: 36,
                    sex: 'Male'
                }]
           },
           methods: {
                createPerson: function() {
                    this.people.push(this.newPerson);
                    // 新增完newPerson物件後,重置newPerson物件
                    this.newPerson = {name: '', age: 0, sex: 'Male'}
                },
                deletePerson: function(index) {
                    // 刪一個數組元素
                    this.people.splice(index,1);
                }
            }
        })
	</script>	
	</body>
</html>

執行結果: