Javascript - Vue - 请求

时间:2022-12-11 00:13:23

本地增删查的一个例子

Javascript - Vue - 请求

<div id="box">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">新增</h3>
        </div>
        <div class="panel-body form-inline">
            <label>
                id:<input type="text" class="form-control" v-model="obj.id" />
            </label>
            <label>
                name:<input type="text" class="form-control" v-model="obj.name" />
            </label>
            <input type="button" value="add" class="btn btn-primary" @click="add" />
            <label>
                search:<input type="text" class="form-control" v-model="keyWords"/>
            </label>
        </div>
    </div>
    <table class="table table-striped table-bordered table-hover table-condensed">
        <tr><th>id</th><th>name</th><th>createTime</th><th>opration</th></tr>
        <!--//呈现的数据由vue对象内部维护的search函数提供,当在搜索框输入数据后,vue对象内部数据keyWords发生变化,则会自动调用search进行数据过滤-->
        <tr v-for="obj in search(keyWords)" :key="obj.id"><td>{{obj.id}}</td><td>{{obj.name}}</td><td>{{obj.time}}</td><td><a href="#" @click.prevent="del(obj.id)">删除</a></td></tr>
    </table>
</div>
vm = new Vue({
    el: "#box",       
    data: {
        keyWords: "",
        obj: { id: null, name: "", time: null },
        list: [
            { id: 1, name: "sam",time:new Date() },
            { id: 2, name: "leo", time: new Date() },
            { id: 3, name: "korn", time: new Date() }
        ]
    },
    methods: {
        add: function () {
            var id = this.obj.id;
            var name = this.obj.name;
            this.list.push({ id: id, name: name,time:new Date() });
        },
        del: function (id) {
            var index=this.list.findIndex((item) => {
                if (item.id == id) return true;
            });
            this.list.splice(index, 1);
        },
        search: function (keyWords) {
            return this.list.filter((item,index) => {
                if (item.name.includes(keyWords)) {
                    return item;
                }
            });             
        }
    }
});

向服务端发起请求

axios

这是官方推荐的新的插件,用于客户端向服务端发送请求。可在axios下载。

<div id="box">
    {{msg}}
    <button @click="sendGet">GetInfo</button> 
        }
    },
    methods: {       
        sendGet: function () {
            var self=this;
            var getObj=axios.get("http://localhost:53385/Handler.ashx", {
                params: self.sendData    
            });
            var endObj= getObj.then(function (response) {
                self.msg = response.data;
            });
            endObj.catch(function (error) {
                self.msg = error.status + error.statusText;
            });
        },
        sendPost: function () {
            var self = this;
            var postObj = axios.post("http://localhost:53385/Handler.ashx", self.sendData);
            var endObj=postObj.then(function (response) {
                self.msg = response.data;
            });
            endObj.catch(function (error) {
                self.msg = error.status + error.statusText;
            });
        }
    }
});
</script>

服务端

ublic class Handler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("OK");
        context.Response.End();
    }  
}

Javascript - Vue - 请求

增删改查实例

<div id="box">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">添加</h3>
        </div>
        <div class="panel-body form-inline">
            <label>
                name:<input type="text" class="form-control" v-model="name" />
            </label>
            <input type="button" value="新增" class="btn btn-primary" @click="add" />
        </div>
    </div>
    <table class="table table-bordered table-hover table-striped">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Date</th>
            <th>Operation</th>
        </tr>
        <tr v-for="obj in list" :key="obj.ID">
            <td>
                {{obj.ID}}
            </td>
            <td>
                {{obj.Name}}
            </td>
            <td>
                {{obj.Date}}
            </td>
            <td>
                <a href="#" :id="obj.ID">编辑</a>
            </td>
        </tr>
    </table>
</div>

服务端需要创建一个模拟数据库存储数据的在内存中可以保持全局唯一的数据对象以便可以在这个对象列表里持续添加数据

public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
    public DateTime Date { get; set; }
    public static List<Employee> GlobalList { get; set; } //全局唯一的员工列表

static Employee()
    {
        GlobalList= new List<Employee>
        {
            new Employee
            {
                ID = 1,
            Date = new DateTime(),
            Name = "寒食"
            },
            new Employee
            {
                ID = 2,
            Date = new DateTime(),
            Name = "山魈"
            },
                new Employee
            {
                ID = 3,
                Date = new DateTime(),
                Name = "李隼"
            }
        };
    }
}

查询

客户端代码

var vm = new Vue({
    el: "#box",
    data: {
        name:null,
        list: [
            { ID: 1, Name: "sam", Date: new Date() }
        ]
    },
    methods: {
        getServerData: function () {
            var self = this;
            axios.get("http://localhost:53385/getAllList.ashx").then(function (response) {
                self.list = response.data;
            });
        }
    },
    created: function () { //vue对象创建完成后开启查询
        this.getServerData();
    }
});

服务端代码

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";
    string listStr = JsonConvert.SerializeObject(Employee.GlobalList);
    context.Response.Write( listStr);
    context.Response.End();
}

新增

客户端代码

var vm = new Vue({
    el: "#box",
    data: {
        name:null,
        list: [
            { ID: 1, Name: "sam", Date: new Date() }
        ]
    },
    methods: {            
        add: function () {
            var self = this;
            axios.post("http://localhost:53385/addData.ashx", { name: this.name }).then(function (response) {
                self.list = response.data;
            });
        }
    }      
});

服务端代码

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";
    //客户端axios对象的post方法模拟了post提交方式,但它提交的是json格式的数据,不能用request.form[]来获取数据
    //以下通过读取流数据来获取客户端提交的json数据
    context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    using (var reader = new System.IO.StreamReader(context.Request.InputStream))
    {
        String jsonData = reader.ReadToEnd();
        var em = new Employee { Date = new DateTime(), Name = JsonConvert.DeserializeObject<Employee>(jsonData).Name };
        var list = Employee.GlobalList;
        list.Add(em);
        var message = string.IsNullOrEmpty(jsonData) ? "error" : JsonConvert.SerializeObject(list);
        context.Response.Write(message);
        context.Response.End();
    }
}

Javascript - Vue - 请求

删改略……

Javascript - 学习总目录