手寫一個Vue前后端分離項目


 

手寫一個Vue前后端分離項目

做一個簡單的聯系人管理,碼雲源碼地址

Vue前端 + C# WebAPI + MySql

  1. 前端選擇單網頁Vue,沒有借助腳手架。
  2. 后端選擇C# 的WebAPI。
  3. 數據庫為MySql。

1. 搭建前端

1.1 創建靜態的vue頁面

預覽界面

  

代碼參考

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link href="css/bootstrap.min.css" rel="stylesheet">
		<script src="js/bootstrap.min.js"></script>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<div id="demo">
			<nav class="navbar navbar-inverse">
				<div class="container-fluid">
					<div class="navbar-brand">Vue 2.0 聯系人單頁應用</div>
				</div>
			</nav>
			<!-- 主頁面 -->
			<div>
				<h4><b>聯系人</b></h4>
			</div>
			<table class="table table-bordered table-hover">
				<thead>
					<tr>
						<td>序號</td>
						<td>姓名</td>
						<td>出生年月</td>
						<td>電話號碼</td>
					</tr>
				</thead>
				<tbody>
					<tr v-for="item in list" :key="item.Id">
						<td>{{item.Id}}</td>
						<td>{{item.Name}}</td>
						<td>{{item.Birthday}}</td>
						<td>{{item.Telephone}}</td>
					</tr>
				</tbody>
			</table>
			<!-- 添加修改頁面  -->
			<div id="editform" class="panel panel-default">
				<div class="panel-heading">
					<h3 class="panel-title">編輯</h3>
				</div>
				<div class="panel-body">
					<form class="form-horizontal" role="form" v-on:submit.prevent>
						<div class="form-group">
							<label class="col-sm-2 control-label">姓名</label>
							<div class="col-sm-10">
								<input class="form-control" v-model="row.Name" id="name" placeholder="輸入姓名">
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">出生日期</label>
							<div class="col-sm-10">
								<input type="date" class="form-control" v-model="row.Birthday" id="birthday">
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 control-label">電話號碼</label>
							<div class="col-sm-10">
								<input class="form-control" v-model="row.Telephone" id="phone">
							</div>
						</div>
						<div class="form-group">
							<div class="col-sm-offset-2 col-sm-10">
								<button @click="newrow" class="btn btn-primary">新增</button>
								<button @click="saverow" class="btn btn-primary">保存</button>
								<button @click="deleterow" class="btn btn-danger">刪除</button>
							</div>
						</div>
					</form>
				</div>
			</div>

			<script>
				new Vue({
					el: "#demo",
					data: {
						row: {
							Id: 0,
							Name: "",
							Birthday: "2020-01-01",
							Telephone: ""
						},
						list: [{
								Id: 5,
								Name: "user2",
								Birthday: "2020-01-01",
								Telephone: "18932180745"
							},
							{
								Id: 6,
								Name: "user3",
								Birthday: "2020-01-01",
								Telephone: "18932180745"
							}
						]
					}
				})
			</script>
	</body>
</html>

1.2 UI 是bootstrap

head中引入

		<link href="css/bootstrap.min.css" rel="stylesheet">
		<script src="js/bootstrap.min.js"></script>

1.3 第三方類庫

head中引入

		<script src="js/underscore.js"></script>
		<script type="text/javascript" src="https://unpkg.com/axios/dist/axios.min.js"></script>
		<script src="https://cdn.bootcdn.net/ajax/libs/qs/6.9.3/qs.min.js"></script>

為了運行速度和版本兼容,一些庫保存到了本地,一般使用公共CDN即可,如貓雲CDN

  • underscore 數組操作
  • axios 請求post等action
  • qs 轉義

1.4 從后端獲取數據

  1. 發送請求 使用axios發送restful請求,需要配合qs將body中的數據格式化。
  2. json和類的轉換。 因為編輯頁面的信息和row綁定了,如果不做操作的話,點擊新增會使選中行的數據也發生變化, 因為js中沒有類的copy,可以將類轉成json字符,再轉成新的類,這樣row 就跟選中行解綁了。

2. 搭建后端

2.1 新建項目

文件-->新建-->項目-->ASP.NET Web應用程序 

選擇模板中的Web API模板(本例選擇的webAPI 模板)

2.2 Nuget引入MySql包

2.3 在Models文件夾下創建model

public class people
    {
        private int id;
        private string name;
        private string birthday;
        private string telephone;

        public int Id { get => id; set => id = value; }
        public string Name { get => name; set => name = value; }
        public string Birthday { get => birthday; set => birthday = value; }
        public string Telephone { get => telephone; set => telephone = value; }
    }

2.4 在Controllers文件夾下創建controller

使用RESTful API接口設計: 查詢 GET :GET /peoples/{userId} 增加 POST:POST /peoples 修改 PUT:PUT /peoples/{userId} 即提供該用戶的所有信息來修改 刪除 DELETE:DELETE /peoples/{userId}

public class PeoplesController : ApiController
    {
        private MySqlConnection GetConnection()
        {
            string connectString = "data source=106.53.98.143;database=fastlink;user id=root;password=admin;pooling=false;charset=utf8";//pooling代表是否使用連接池
            MySqlConnection conn = new MySqlConnection(connectString);
            conn.Open();
            return conn;
        }
        [Route("api/peoples")]
        // GET api/peoples
        public IEnumerable<people> Get()
        {
            List<people> list = new List<people>();
            using (MySqlConnection conn = this.GetConnection())
            {
                using (MySqlCommand com = new MySqlCommand())
                {
                    com.Connection = conn;
                    com.CommandText = "select * from peoples";
                    MySqlDataReader reader = com.ExecuteReader();
                    while (reader.Read())
                    {
                        people line = new people();
                        int id = 0;
                        int.TryParse(reader["id"].ToString(), out id);
                        line.Id = id;
                        line.Name = reader["name"].ToString();
                        DateTime dt = DateTime.MinValue;
                        DateTime.TryParse(reader["birthday"].ToString(), out dt);
                        line.Birthday = dt.ToString("yyyy-MM-dd");
                        line.Telephone = reader["telephone"].ToString();
                        list.Add(line);
                    }
                }
            }
            return list.ToArray();
        }
        [HttpGet]
        //注意:如果想通過Get請求AA/index/names,可以在Get前面加Route。
        [Route("api/peoples/{name}")]
        // GET api/peoples/zhangsan
        public people Get(string name)
        {
            people line = new people();
            using (MySqlConnection conn = this.GetConnection())
            {
                using (MySqlCommand com = new MySqlCommand())
                {
                    com.Connection = conn;
                    com.CommandText = "select * from peoples" + " where name=@name ";
                    com.Parameters.AddWithValue("@name", name);
                    MySqlDataReader reader = com.ExecuteReader();
                    if (reader.Read())
                    {

                        int id = 0;
                        int.TryParse(reader["id"].ToString(), out id);
                        line.Id = id;
                        line.Name = reader["name"].ToString();
                        DateTime dt = DateTime.MinValue;
                        DateTime.TryParse(reader["birthday"].ToString(), out dt);
                        line.Birthday = dt.ToString("yyyy-MM-dd");
                        line.Telephone = reader["telephone"].ToString();

                    }
                }
            }
            return line;
        }
        //create
        [HttpPost]
        [Route("api/peoples")]
        // POST: api/Users
        public void Post([FromBody]people line)
        {
            using (MySqlConnection conn = this.GetConnection())
            {
                using (MySqlCommand com = new MySqlCommand())
                {
                    com.Connection = conn;
                    com.CommandText = "insert into peoples(name, birthday, telephone) values (@name, @birthday, @telephone) ";
                    com.Parameters.AddWithValue("@name", line.Name);
                    com.Parameters.AddWithValue("@birthday", line.Birthday);
                    com.Parameters.AddWithValue("@telephone", line.Telephone);
                    com.ExecuteNonQuery();
                }
            }
        }

        [HttpPut]
        [Route("api/peoples/{name}")]
        // PUT: api/Users/5
        public void Put(string name, [FromBody]people line)
        {
            using (MySqlConnection conn = this.GetConnection())
            {
                using (MySqlCommand com = new MySqlCommand())
                {
                    com.Connection = conn;
                    com.CommandText = "update peoples set birthday=@birthday, telephone=@telephone where name=@name ";
                    com.Parameters.AddWithValue("@name", name);
                    com.Parameters.AddWithValue("@birthday", line.Birthday);
                    com.Parameters.AddWithValue("@telephone", line.Telephone);
                    com.ExecuteNonQuery();
                }
            }
        }

        [HttpDelete]
        [Route("api/peoples/{name}")]
        // DELETE: api/Users/5
        public void Delete(string name)
        {
            using (MySqlConnection conn = this.GetConnection())
            {
                using (MySqlCommand com = new MySqlCommand())
                {
                    com.Connection = conn;
                    com.CommandText = "delete from peoples where name=@name ";
                    com.Parameters.AddWithValue("@name", name);
                    com.ExecuteNonQuery();
                }
            }
        }
    }

2.5 跨域

使用nuget包獲取Microsoft.AspNet.WebApi.Cors 
在App_Start\WebApiConfig.cs中加入代碼
			//跨域配置
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

2.6 引入swagger

非必須,只是更好的管理接口,可跳過。使用nuget包獲取Swashbuckle(swagger的包)並安裝。

 

2.7 Postman

用於調試后端接口 

如圖,已經導出SPA.postman_collection.json,見attachment文件夾。

3. MySql數據庫

  1. 新建數據庫fastlink,字符集為utf8mb4
  2. 執行sql語句,sql語句見附件文件夾。
CREATE TABLE `peoples` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `birthday` varchar(50) DEFAULT NULL,
  `telephone` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
INSERT INTO `peoples` VALUES ('1', 'user51', '2020-01-01', '18932180745');
INSERT INTO `peoples` VALUES ('2', 'kevin', '2020-01-01', '18932180745');

4. 調試

通過VS2019啟動webAPI,瀏覽器會轉向 鏈接https://localhost:44384 不同瀏覽器端口號可能不同。 增加/swagger 可以查看生效的APIs。
 
此時可以啟動Postman進行接口調用測試。
如果接口都正常,則通過瀏覽器打開index網頁,測試增刪改查功能。

至此,完成前后端分離的開發。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM