Asp.net+Vue+EmelentUI的實現(一)框架搭建


原文鏈接:https://blog.csdn.net/xxdddail/article/details/89876055
 
vue對於web端的開發優勢是很明顯的,特別是單頁應用,響應、數據等都很明顯,而且開發效率也高,又有很多資料可查、有社區的支持。但vue對於開發較大的項目時,則會顯得笨重,因為編譯成了單頁應用,非常臃腫,首次加載變的很慢。而且在使用VS來開發時,雖然VS可以創建vue的項目,但是基於node.js來編譯的,不好操作,而且經常出現卡死現象,於是就考慮有沒有其他的方式來應用vue。
vue本質上是一個對UI的渲染,可以認為是view的渲染層,而emelent ui是基於vue的控件庫,本上相關的js則可正常工作,對於網網請求可以通過vue-resource來達成,再加上asp.net構建的webapi來實現服務的請求,那么基本上是可以成型的,基於這樣的思路,於是有了后面的開發實踐。
1.新建一個空的web項目
2.使用nuget安裝vue、vue-resource、vue.js.element.ui
 
安裝后的項目可以看到ElementUI、vue、vue-resource
 
3.創建App_Start文件夾,添加WebApiConfig.cs的類,添加System.Web.Http的引用
 
WebApiConfig.cs的代碼如下
/// <summary>    /// webapi的配置    /// </summary>    public static class WebApiConfig    {        /// <summary>        /// 注冊        /// </summary>        /// <param name="config"></param>        public static void Register(HttpConfiguration config)        {            // Web API 配置和服務             // Web API 路由            config.MapHttpAttributeRoutes();             config.Routes.MapHttpRoute(                name: "DefaultApi",                routeTemplate: "api/{controller}/{action}/{id}",                defaults: new { id = RouteParameter.Optional }            );        }    }
使用nuget安裝AspNet.WebApi,否則config.MapHttpAttributeRoutes會報錯。
 
4.添加Global.asax
 
使用nuget安裝AspNet.WebApi.WebHost
 
在Global類的Application_Start中添加代碼
   protected void Application_Start(object sender, EventArgs e)        {            GlobalConfiguration.Configure(WebApiConfig.Register);        }
5.創建Controller文件夾,添加LoginController類用於用戶的登入
 
LoginController類的代碼如下
 public class LoginController : ApiController    {         /// <summary>        /// 登錄        /// </summary>        /// <param name="account"></param>        /// <param name="password"></param>        /// <returns></returns>        [HttpGet]        public BaseDataPackage<UserData> Login(string account,string password)        {            //使用account和password驗證用戶             UserData userData = new UserData();            userData.UserGuid = Guid.NewGuid().ToString();            userData.UserName = "測試用戶";             var result = new BaseDataPackage<UserData>();            result.Data = userData;            result.Status = ApiStatusCode.OK;            result.Message = "登錄成功";            return result;        }    }
/// <summary>    /// 狀態碼    /// </summary>    public class ApiStatusCode    {        /// <summary>        /// OK        /// </summary>        public const int OK = 0;         /// <summary>        /// 失敗        /// </summary>        public const int FAIL = 1;         /// <summary>        /// 異常        /// </summary>        public const int EXCEPTION = 2;    }
 public class BaseDataPackage<T>    {        public int Status { get; set; }        public string Message { get; set; }        public T Data { get; set; }             }
6.建立Login文件夾,添加界面文件Login.aspx
 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="AspNetVueElementUI.Login.Login" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <script src="/Scripts/vue.js"></script>    <script src="/Scripts/vue-resource.js"></script>    <script src="/Scripts/ElementUI/element-ui.js"></script>    <script src="/Scripts/kit.js"></script>    <script src="/Scripts/global.js"></script>    <link href="/Content/ElementUI/element-ui.css" rel="stylesheet" />    <title>管理系統</title>    <style>        .el-row {            margin-bottom: 20px;        }         .login-box {            margin-top: 20%;            margin-left: 40%;        }    </style></head><body>    <div class="login-box" id="app">        <el-row>            <el-col :span="8">                <el-input id="name" v-model="name" placeholder="請輸入帳號">                    <template slot="prepend">                        帳號                    </template>                </el-input>            </el-col>        </el-row>        <el-row>            <el-col :span="8">                <el-input id="password" v-model="password" type="password" placeholder="請輸入密碼">                    <template slot="prepend">                        密碼                    </template>                </el-input>            </el-col>        </el-row>        <el-row>            <el-col :span="8">                <el-button id="login" v-on:click="check" style="width:100%" type="primary" v-loading.fullscreen.lock="logining">登錄</el-button>            </el-col>        </el-row>    </div></body> <script type="text/javascript">    window.onload = function () {        new Vue({            el: '#app',            data: {                name: '',                password: '',                logining: false            },            methods: {                check: function (event) {                    //獲取值                    var name = this.name;                    var password = this.password;                    if (name == '' || password == '') {                        this.$message({                            message: '賬號或密碼為空!',                            type: 'error'                        })                        return;                    }                    var turnUrl = kit.getQueryString('ReturnUrl');                    if (turnUrl == undefined || turnUrl == null || turnUrl.length <= 0) {                        turnUrl = "/default.aspx";                    }                    var url = '/API/Login/Login?account=' + name + "&password=" + password;                    this.logining = true;                    this.$http.get(url).then(function (res) {                        var result = res.body;                        this.$message({                            message: result.Message,                            type: result.Status == 0 ? 'success' : 'error'                        })                        this.logining = false;                        if (result.Status == 0) {                            global.setUser(result.Data.UserGuid, result.Data.UserName);                            window.location = turnUrl;                        }                    }, function (e) {                        console.log(e);                        this.$message({                            message: '登錄異常',                            type: 'error'                        })                        this.logining = false;                    });                }            }        })    }</script></html>
7.添加默認頁default.aspx
 
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="AspNetVueElementUI._default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title></head><body>    <div>        歡迎使用    </div></body></html>
8.運行代碼
 
 
通過以上的步驟,就實現了簡單的框架搭建,Login.aspx使用vue和element ui來實現登錄的界面,controller文件夾下實現登錄訪問的api,但要對整個網站進行登錄驗證,則要使用asp.net的驗證機制,請參看《Asp.net+Vue+EmelentUI的實現(二)登錄驗證》


免責聲明!

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



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