vue-resource实现数据的绑定、添加、删除

时间:2023-12-23 18:10:43

vue-resource实现数据的绑定、添加、删除

 <!DOCTYPE html>
<html lang="en">
<head>
<title>简单用户管理</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!--vue-resource是基于vue的,应在引用vue之后引用vue-resource-->
<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.1"></script>
</head>
<body>
<div id="app">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">基于vue.js的简单用户管理</h3>
</div>
<div class="panel-body form-inline ">
<label>
<!--v-focus为自定义指令的调用,元素自动获得焦点-->
username:
<input type="text" class="form-control" v-model="username" v-focus>
</label>
<label>
userpwd:
<input type="text" class="form-control" v-model="userpwd">
</label>
<button class="btn btn-primary" @click="add()">Create</button>
</div>
</div>
<table class="table table-hover table-bordered table-striped">
<thead>
<tr>
<th>username</th>
<th>userpwd</th>
<th>Operation</th>
</tr>
</thead>
<tbody>
<tr v-for="list in lists" :key="list.userid">
<td>{{list.username}}</td>
<td>{{list.userpwd}}</td>
<td>
<!--prevent为阻止事件的默认行为-->
<a href="" @click.prevent="del(list.userid)">Delete</a>
</td>
</tr>
</tbody>
</table>
</div>
</body>
<script>
Vue.http.options.root = 'http://localhost:18227/' //设置全局请求根路径
Vue.http.options.emulateJSON = true; //启用from格式的请求 //自定义指令
Vue.directive('focus', {
inserted: function (el) {
el.focus()
},
}); new Vue({
el: '#app',
data: {
username: "",
userpwd: "",
lists: []
},
methods: {
del(userid) {
this.$http.get('Index/DelJson?userid=' + userid).then((result) => {
if (result.body.State === 1) {
this.getAllLists();
}
}).catch((err) => {
alert("获取数据失败");
});
},
add() {
var list = { username: this.username, userpwd: this.userpwd };
this.$http.post('Index/AddJson', list, {}).then((result) => {
this.username = this.userpwd = "";
if (result.body.State === 1) {
this.getAllLists();
}
}).catch((err) => {
alert("获取数据失败");
});
},
getAllLists() {
this.$http.get('Index/ReturnJson').then((result) => {
this.lists = result.body;
}).catch((err) => {
alert("获取数据失败");
});
}
},
created() {
console.log("第一步")
// 实例初始化完成
this.getAllLists();
},
})
</script>
</html>

 服务端代码为C#,以下是控制器

         public string ReturnJson()
{
var userlist = db.User.Where<User>(u => true);
return JsonConvert.SerializeObject(userlist);
}
public JsonResult AddJson(User user)
{
MsgJson m = new MsgJson();
db.User.Add(user);
if (db.SaveChanges() > )
{
m.Msg = "请求成功";
m.State = ;
}
else {
m.Msg = "请求失败";
m.State = ;
}
return Json(m);
}
public JsonResult DelJson(string userid)
{
int did = int.Parse(userid);
List<User> userlist =db.User.Where(u => u.userid == did).ToList();
User user = userlist[];
db.User.Remove(user);
MsgJson m = new MsgJson();
if (db.SaveChanges() > )
{
m.Msg = "请求成功";
m.State = ;
}
else
{
m.Msg = "请求失败";
m.State = ;
}
return Json(m, JsonRequestBehavior.AllowGet);
}