美文网首页Restful APIWeb前端之路程序员
Vue.JS 联系人单页应用(五) - 从前端到后端

Vue.JS 联系人单页应用(五) - 从前端到后端

作者: 程序员长春 | 来源:发表于2017-02-06 16:13 被阅读1641次

    前言

    在前面四篇文章中,我们搭建了一个纯粹的客户端应用,数据保存在客户端内存中。同时,对于表格和表单的自动化,进行了一些尝试。
    正常的生产环境中,数据通常存放在数据服务器上,前端需要完成的工作还包括,访问后端API接口,实现真正的CRUD。而实现此功能的一大利器则是AJAX。
    这篇文章是从前端到后端的一个分界线,因此我们将尽量减少复杂度,希望让前端和后端都能看懂,你的同伴需要什么。

    Axios 介绍

    Axios 开源代码在 Github

    Promise based HTTP client for the browser and node.js
    运行在浏览器及node.js上,基于Promise的HTTP 客户端工具

    项目改造

    前端改造
    1. HTML
      受益于Vue的组件化编程,我们无需对HTML文件进行任何修改,当然如果你还没有加入Axios的引用,那么此时需要在HTML中添加Axios引用。
    <script type="text/javascript" src="https://unpkg.com/axios/dist/axios.min.js"></script>
    
    1. Javascript
    data: {
        title: '联系人',
        columns: [{
          name: 'id',
          iskey: true
        }, {
          name: 'name',
          caption: '姓名',
        }, {
          name: 'birthday',
          caption: "出生日期",
          type: 'date'
        }, {
          name: 'phone',
          caption: '电话'
        }],
        row: {
          id: 0,
          name: '',
          birthday: '',
          phone: ''
        },
        list: [{
          id: 1,
          name: '深圳有事Q我',
          birthday: '2000-09-10',
          phone: '2345678'
        }, {
          id: 2,
          name: '上海没事别烦我',
          birthday: '1980-01-22',
          phone: '1293587023'
        }, {
          id: 3,
          name: '北京蓝色医生',
          birthday: '1990-02-01',
          phone: '1332345876'
        }]
      },
    -------------------------------- 我是修改隔离线 ---------------------------------
    data: {
        title: '联系人',
        columns: [],
        ......
        list: []
      },
    mounted: function(){
        let vm=this
        //ID=0时,返回TableSchema
        axios.get('/api/contacts/0')
             .then(function (response) {
               vm.columns.push.apply(vm.columns,response.data)
              })
             .catch(function (error) {
                console.log(error);
             })
        //取出所有联系人
        axios.get('/api/contacts')
             .then(function(response) {
               vm.list.push.apply(vm.list, response.data)
             })
             .catch(function(error) {
               console.log(error)
             })
      },
    

    2.1 控制表格和表单的所有数据,都存放在columns和list这两个数组中。
    2.2 mounted是Vue组件事件,详细说明看 官网
    2.3 Axios 官网使用说明

    后端实现

    打开Visual Studio 2013,创建一个基本的WebAPI项目,具体过程可以参考 十分钟快速实现WebAPI

    1. 业务实体 - ViewModel
    Public Class ContactViewModel
        Public Sub New(ByVal id As Integer,
                       ByVal name As String,
                       ByVal birthday As Nullable(Of DateTime),
                       ByVal phone As String)
            Me.id = id
            Me.name = name
            Me.birthday = birthday
            Me.phone = phone
        End Sub
        Public Property id As Integer
        Public Property name As String
        Public Property birthday As Nullable(Of DateTime)
        Public Property phone As String
    End Class
    '---------------------------'
    Public Class TableSchema
        Public Property name As String
        Public Property caption As String
        Public Property type As String
        Public Property iskey As Boolean
    End Class
    

    定义两个类,TableSchema用于保存数据结构,ContactViewModel用于保存联系人信息。

    1. 新建联系人API控制器ContactsController
    Public Class ContactsController
        Inherits ApiController
    
        Private m_ContactList As New List(Of ContactViewModel)
    
        Public Sub New()
            With m_ContactList
                .Add(New ContactViewModel(1, "深圳有事Q我", CDate("2000-09-10"), "2345678"))
                .Add(New ContactViewModel(2, "上海没事别烦我", CDate("1980-01-22"), "1293587023"))
                .Add(New ContactViewModel(3, "北京深蓝医生", CDate("1990-02-01"), "1332345876"))
            End With
        End Sub
    
        ' GET api/contact
        Public Function GetValues() As IEnumerable(Of ContactViewModel)
            Return m_ContactList
        End Function
    
        ' GET api/contact/5
        Public Function GetValue(ByVal id As Integer) As Object
            If id = 0 Then
                Return GetSchema()
            Else
                Return m_ContactList.Find(Function(c) c.ID = id)
            End If
        End Function
    
        Private Function GetSchema() As IEnumerable(Of TableSchema)
            Dim ls = New List(Of TableSchema)
    
            With ls
                .Add(New TableSchema With {.name = "id", .iskey = True})
                .Add(New TableSchema With {.name = "name", .caption = "姓名"})
                .Add(New TableSchema With {.name = "birthday", .caption = "出生日期", .type = "date"})
                .Add(New TableSchema With {.name = "phone", .caption = "电话"})
            End With
    
            Return ls
        End Function
    
        ' POST api/contact
        Public Sub PostValue(<FromBody()> ByVal value As String)
    
        End Sub
    
        ' PUT api/contact/5
        Public Sub PutValue(ByVal id As Integer, <FromBody()> ByVal value As String)
    
        End Sub
    
        ' DELETE api/contact/5
        Public Sub DeleteValue(ByVal id As Integer)
    
        End Sub
    End Class
    

    在这段代码中,做了以下几件事,
    2.1 控制器构造器中,初始化一个联系人列表。
    2.2 GetValues返回全部联系人。
    2.3 GetValue(Byval id as INteger)做了一点小小的处理,当id=0时,返回表结构,当id<>0时,返回单个联系人信息。
    2.4 PostValue,PutValue, DeleteValue暂时不做处理。

    1. 加入Index.html和相应的javascript。
      把我们之前完成的html页面和Javascript代码复制到WebAPI项目中,html页面命名为Index.html。

    总结

    现在是见证奇迹的时候了,按下F5,可以看到辛苦了几十分钟的工作。
    在本文中,我们做了几件小小的事情。

    • 修改javascript代码,加入Axios调用API代码。
    • 创建WebAPI项目,加入ContactsController联系人API
    • 在定义联系人实体类时,采用了javascript常用的CamelCase变量命名方式,以避免Json序列化时需要处理的复杂性。
    • 日期显示还存在BUG,不过这个应该交给后端程序员去处理,包括上面的变量大小写问题。

    系列文章目录

    1. 列表显示
    2. 表单显示
    3. 表单CRUD
    4. Vue组件化
    5. 从前端到后端

    相关文章

      网友评论

      • c47209eb4446:hi,有源码分享吗,最后这份前后端分离的整个工程,我刚入门,你的这篇文章很适合我现在的学习阶段
        c47209eb4446: @程序员长春 哦哦
        程序员长春:全部的源码都在文章里面,前端的在JSFiddler上面,后端我只是实现了一个很简单的WebAPI而已。

      本文标题:Vue.JS 联系人单页应用(五) - 从前端到后端

      本文链接:https://www.haomeiwen.com/subject/mxqeittx.html