<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>vue學習 語法demo1</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="application/javascript" src="jquery-1.11.2.min.js"></script>
</head>
<body>
<div id="app">
<table>
<tr>
<th>序號</th>
<th>名字</th>
<th>年齡</th>
<th>性別</th>
<th>愛好</th>
<th>操作</th>
</tr>
<tr v-for="(item,index) in users">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>{{item.sex}}</td>
<td>{{item.hobby}}</td>
<td><a href="#" @click="edit(index)">編輯</a></td>
<td><a href="#" @click="remove(index)">刪除</a></td>
</tr>
<tr>
<td><input type="" v-model="id" ></td>
<td><input type="" v-model="name" ></td>
<td><input type="" v-model="age" ></td>
<td><input type="" v-model="sex" ></td>
<td><input type="" v-model="hobby" ></td>
<td>
<a href="#" @click="add()" v-if="is_add">添加</a>
<a href="#" @click="save()" v-if="is_edit">編輯</a>
</td>
</tr>
</table>
</div>
<script src="vue.js"></script>
<script>
var app = new Vue({
el: '#app',
data: {
users:[
{id:1,name:"張明",age:21,sex:"男",hobby:"上網"},
{id:2,name:"金敏",age:21,sex:"女",hobby:"打游戲"},
{id:3,name:"趙燕",age:20,sex:"女",hobby:"看書"},
{id:4,name:"鄭陽",age:25,sex:"男",hobby:"抽煙,喝酒"}
],
id:"",
name:"",
age:"",
sex:"",
hobby:"",
is_add:true,
is_edit:false
},
filter:{
},
watch:{
},
methods: {
edit: function (index) {
console.log(index);
var user = this.users[index];
this.id=user.id;
this.name=user.name;
this.age=user.age;
this.sex=user.sex;
this.hobby=user.hobby;
this.is_edit=true;
this.is_add=false;
},
add: function()
{
this.users.push({id:this.id,name:this.name,age:this.age,sex:this.sex,hobby:this.hobby});
this.id="";
this.name="";
this.sex="";
this.age="";
this.sex="";
this.hobby="";
},
save:function(){
var that = this;
$.each(this.users,function(i,item){
if(item.id==that.id){
item.name=that.name;
item.age=that.age;
item.sex=that.sex;
item.hobby=that.hobby;
}
});
this.id="";
this.name="";
this.sex="";
this.age="";
this.sex="";
this.hobby="";
this.is_add=true;
},
remove:function(index){
this.users.splice(index, 1);
}
}
});
</script>
</body>
</html>
運行效果如下