MVVM前后分離輕量級框架應用juicer和doT.js


前言
      前后端開發分的越來越細化,為了方便前端工程師更好的調試后端工程師嵌套的代碼,前后分離技術就出現了,簡單理解其實就是Ajax異步將數據提供給JavaScript,由JavaScript進行迭代展現渲染成想要的效果,這樣做還可以使頁面數據異步化,頁面展現時只需要加載頁面結構及js、css、image等,而這些靜態文件還可以通過CDN進行優化,縮短了打開頁面白屏的時間,進一步加快了用戶看到頁面的速度,優點還是非常多的。
     前端MVVM框架有很多Vue.js、Angular2.js、React.js、juicer.js(ali)、artTemplate.js(tencent)、doT.js等等有很多,各有優勢,前三個屬於重量級功能大而全,而我的需求只需要簡單迭代即可,所以選擇后三個輕量級的,推薦使用juicer.js是阿里的而且支持Node.js,語法不太抽象很容易理解。
     無論那種框架實際應用時主要的功能就是循環、判斷、輸出這三個,下面我們根據日常需要撰寫一下應用實例。
一、juicer的應用
官網地址:http://juicer.name/
1、基本語法
//變量輸出${變量}
${var flag = "test"}

//變量避免轉義輸出$${變量}

//循環{@each}...{@/each}
{@each list as item}
     //do something...
     ${item.prop}
{@/each}
{@each list as item, index}
     //do something...
     ${index}
     //此處的index代表當前索引
{@/each}

//判斷{@if}...{@/if}
{@if ${item.prop == 'a'}}
     //do something...
{@else if}
     //do something...
{@else}
     //do something...
{@/if}

//注釋{# 內容}

//輔助循環{@each i in range(m, n)}
{@each i in range(5, 10)}
     ${i} //輸出5 6 7 8 9
{@/each}

//嵌套模板{@include tpl, data}

 2、引入js文件

<script type="text/javascript" src="~/static/js/jquery/jquery-min.js"></script><!--可以不用jquery,使用默認js語法即可-->
<script type="text/javascript" src="~/static/js/juicer/juicer-min.js"></script>

3、設置自定義標簽

不同開發語言可能導致對不同的模板符號編譯錯誤,我們可以自定義模板符號規則
//頁面加載后設置自定義標簽
$(function () {
    juicer.set({
        'tag::operationOpen': '{*',     //操作標簽-開
        'tag::operationClose': '}',     //操作標簽-關
        'tag::interpolateOpen': '${',   //變量標簽-開
        'tag::interpolateClose': '}',   //變量標簽-關
        'tag::noneencodeOpen': '$${',   //禁止轉義標簽-開
        'tag::noneencodeClose': '}',    //禁止轉義標簽-關
        'tag::commentOpen': '{#',       //注釋標簽-開
        'tag::commentClose': '}',       //注釋標簽-關
        'cache': true,          //[默認開啟]是否緩存模板編譯結果,開啟后會避免同一模板多次數據渲染時重復編譯模板,減少編譯模板所耗的時間
        'script': true,         //[默認開啟]是否清除空白,清除模板中的空白,包括換行、回車等
        'error handling': true, //[默認開啟]是否處理錯誤
        'detection': true       //[默認開啟]是否檢測變量是否定義,開啟后如果變量未定義,將用空白字符串代替
    });
})

 4、編寫展示模版

<script id="tplAccountAll" type="text/template">
    <thead>
        <tr class="bg-warning">
            <th class="text-center">賬號</th>
            <th class="text-center">現金余額</th>
            <th class="text-center">凍結資金</th>
            <th class="text-center">賬號描述</th>
            <th class="text-center">綁定手機</th>
            <th class="text-center">綁定郵箱</th>
            <th class="text-center">獨立核算</th>
            <th class="text-center">狀態</th>
            <th class="text-center">創建時間</th>
            <th class="text-center">操作</th>
        </tr>
    </thead>
    {*each list as item}
    <tr>
        <td class="text-primary">${item.AccountNo}</td>
        <td class="text-right text-success">${item.Balance.toFixed(2)}</td>
        <td class="text-right text-success">${item.FreezeBalance.toFixed(2)}</td>
        <td class="text-center">${item.AccountDescription}</td>
        <td class="text-center">${item.Mobile}</td>
        <td class="text-center">${item.Email}</td>
        <td class="text-center">${item.IsSelfFinanced}</td>
        <td class='${item.Status == 1 ? "text-success" : "text-danger"} text-center'>${item.StatusName}</td>
        <td class="text-center">${item.CreateTime}</td>
        <td class="text-center">
            {*if item.AccountNo != item.CustomerNo}
            <a href="javascript:void(0)" onclick="updateStatus('${item.AccountNo}',${item.Status}, this)">[${item.StatusOperation}]</a>
            {*/if}
            <a href="~/AccountManage/GrantRuleToAccount?AccountNo=${item.AccountNo}" target="_blank">[分配權限]</a>
            <a href="~/AccountManage/SetCreditLineLimit?AccountNo=${item.AccountNo}" target="_blank">[授信限額設定]</a>
            <a href="javascript:void(0)" onclick="showPayBusInfo('${item.AccountNo}')">[查看授信余額]</a>
        </td>
    </tr>
    {*/each}
</script>

5、渲染模版展示內容

<script type="text/javascript">
    $(function () {
        $.post("/AccountManage/AjaxGetAccountListData", function (data) {
            data = { list: JSON.parse(data) };
            console.log(data);
            //獲取模版
            var tplAccountAll = $("#tplAccountAll").html();
            //渲染數據
            var htmlContent = juicer(tplAccountAll, data);
            //顯示內容
            $("#showAccountAll").html(htmlContent);
        });
    })
</script>

 

二、doT的應用

 1、基本語法 
{{= }} for interpolation 輸出
{{ }} for evaluation 代碼塊
{{~ }} for array iteration 迭代
{{? }} for conditionals 條件
{{! }} for interpolation with encoding 編碼輸出
{{# }} for compile-time evaluation/includes and partials
{{## #}} for compile-time defines

 2、引入js文件

<script src="jquery.min.js"></script>
<script src="doT.min.js"></script>

 3、編寫展示模板

<script id="tmpBuyAndBuy" type="text/x-dot-template">
    {{ if(it && it.length > 0){ }}
        <div class="guessTit">
            <div class="guessLine abs"></div>
            <span class="abs w200">根據購物車的商品,為您推薦</span>
        </div>
        <div class="guseeBig">
            <p class="t2">90%的媽媽還買了以下商品</p>
        </div>
        <div class="guessLoveCon">
            <ul class="guessCon clearfix">
                {{ for(var i = 0; i < it.length; i++){ }}
                {{ var item = it[i]; }}
                <li>
                    <a href="{{=item.GoodsShowUrl}}">
                        <div class="hotProImg rel">
                            <img src="{{=item.GoodsImgUrl}}" alt="">
                            {{?item.NationPic}}
                            <div class="hotProflag abs"><img src="{{=item.NationPic}}" alt=""></div>
                            {{?}}
                        </div>
                        <div class="gupt">{{=item.SellingPoint}}</div>
                        <div class="guessProTit gray">{{=item.GoodsName}}</div>
                        <div class="guessMoney clearfix">
                            <span class="s1"><i>{{=item.GoodsPriceInteger}}</i>.{{=item.GoodsPriceDecimal}}</span>
                            <span class="s2">¥{{=item.MarketPrice.toFixed(2)}}</span>
                        </div>
                    </a>
                </li>
                {{ } }}
            </ul>
        </div>
    {{ } }}
</script>

4、渲染模版展示內容

<script type="text/javascript">
    var jsBuyAndBuy = jsBuyAndBuy || {};
    jsBuyAndBuy.GetData = function (goodsids) {
        if (goodsids) {
            $.post("/Cart/AjaxBuyAndBuy", { goodsIds: goodsids }, function (data) {
                //注入模板
                var evalText = doT.template($("#tmpBuyAndBuy").text());
                //填充內容
                $("#cntBuyAndBuy").html(evalText($.parseJSON(data)));
                //隱藏Loading
                $("#loadBuyAndBuy").hide();
            });
        }
    }   
</script>

 我這里只簡單介紹一下使用方法,這些基本夠我日常應用了,如果有更高難度的需求,還請查閱官方文檔,此類模板使用方法都大同小異,學會一個其他的也就都會了,區別只有各自的語法標記不同而已。


免責聲明!

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



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