搜尋
首頁微信小程式小程式開發藝龍微信小程式框架元件實例程式碼

藝龍微信小程式框架元件實例程式碼

Mar 16, 2017 pm 01:34 PM
微信小程式

由於身處於線上旅遊業,對OTA的行業動態都比較關心一些,前陣子研究體驗了一下藝龍的微信小程序,雖然有些美中不足,但是小程序的架構組件還是非常好的,所以今天我們就來簡單看看藝龍微信小程式框架元件。
首先,我們將藝龍微信小程式的框架元件分為以下四個部分來分析:
1.局部元件
2.獨立元件
3.整合元件
4.網路請求
先看三張的動態效果圖:
整體而言,其目錄結構如下:

[AppleScript] 純文字檢視複製程式碼

├── README.MD
├── app.js
├── app.json
├── app.wxss
├── components
├── image
├── pages
├── service
└── utils
    ├── api.js
    ├── cookie.js
    ├── data-center.js
    ├── overwrite.js
    ├── page-events.js
    ├── path.js
    ├── promise.js
    └── service.js

框架使用說明

  • 框架對所有微信原生api進行了一層包裝,以便管控和擴展。

[AppleScript] 純文字檢視複製程式碼

//index.js
var api = require("./utils/api.js")();
api.login({
    success: function(res) {
        console.log(res);
    }
});

[AppleScript] 純文字檢視複製程式碼

//index.js
var api = require("./utils/api.js")();
api.login({
    success: function(res) {
        console.log(res);
    }
});
  • 對於後端介面,框架提供service層進項管理,介面回傳一個Promise物件

[AppleScript] 純文字檢視複製程式碼

//demo.js
var Service = require("../utils/service.js");
module.exports = {
    GetTime: Service({
        url: 'https://xxx.xxx.xxx/api/getserverdate/',
        params: [], //参数列表
        method: 'GET',
        noLoading: true,
        mockData: function() { //模拟数据
            return new Date();
        },
        dataTransform: function(data) { //适配处理
            return data;
        }
    })
};

[AppleScript] 純文字檢視複製程式碼

//index.js
var service = require('service/demo'); //框架约定,所有的后端接口,要注册到对应的service文件中
var serverDate = service.GetTime( /*service可配置参数列表,这里传入相对应的参数*/ ).then(function(date) {
    that.setData({
        serverDate: date
    });
});
  • 小程式不支援cookie機制,若要相容於現有後端cookie處理(不做改動),可使用框架模擬的cookie機制。

[AppleScript] 純文字檢視複製程式碼

//index.js
var COOKIE = require('./cookie.js');
var expire = new Date().getTime() + res.expire * 1000;
COOKIE.set(key, value, expire);

[AppleScript] 純文字檢視複製程式碼

//service.js
//...
headers["Cookie"] = Cookie.getAll(); //用户cookie将随http请求发送至服务器
//...
  • Page( ) 函數用來註冊一個頁面。接受一個object參數,其指定頁面的初始資料、生命週期函數、事件處理函數等,框架對Page做了重寫,這樣可以方便的使用擴展能力,使用時僅需將原廠的業務代碼用包裝器包裝即可。

[AppleScript] 純文字檢視複製程式碼

//微信小程序原生页面注册形式
Page({
    data: {},
    onLoad: function() {}
});
//框架重写注册形式
var dirname = 'pages/index',
    overwrite = require('../../utils/overwrite.js');
(function(require, Page) { //重写require、Page
    Page({
        data: {},
        onLoad: function() {}
    });
})(overwrite.require(require, dirname), overwrite.Page);
  • globalData監聽,框架支援全域事件監聽機制

#[AppleScript] 純文字檢視複製程式碼

//index.js
var dirname = 'pages/index',
    overwrite = require('../../utils/overwrite.js');
(function(require, Page) {
    //获取应用实例
    var app = getApp();
    var service = require('service/demo');
    Page({
        data: {
            indate: '',
            indateText: ''
        },
        onLoad: function() {
            this.listenerGlobalData('indate', function(indate) {
                this.data.indate = indate
                this.data.indateText = new Date(indate).format('MM-dd')
            }.bind(this));
        }
    })
})(overwrite.require(require, dirname), overwrite.Page);
  • 事件機制,頁間跳轉可以傳遞數據,框架支援頁間傳遞資料的同時,也可以透過跳轉介面傳回的事件物件監聽自訂事件。

[AppleScript] 純文字檢視複製程式碼

//index页面
var event = api.Navigate.go({
    url: '../list/index',
    params: {
        name: 'billy'
    }
});
event.on("listok", function(params) {
    console.log(params);
});

[AppleScript] 純文字檢視複製程式碼

//http页面
Page({
    onLoad: function(data) {
        if (data.name === 'billy') {
            this.fireEvent("listok", 'hello ' + data.name);
        }
    }
});

元件使用說明

  • #內建元件

框架重寫Page建構方法,內建了一些常用的元件,例如alert、picker、setLoading,其中alert和setLoading 內部分別封裝了原生的wx.showModal 、wx.showToast,封裝使得呼叫參數結構化,方便業務使用,使用時不用引入頁面結構,直接調用即可;picker則需要先引入頁面中表現層結構,依照配置要求傳遞配置項。

[AppleScript] 純文字檢視複製程式碼

//setLoading
this.setLoading(true);//ture/false
//picker 引入表现层结构
<!--index.wxml-->
<view class="container">
    <view class="userinfo">
        <text class="userinfo-nickname">{{current}}</text>
    </view>
    <include src="../../components/base.wxml" />
</view>
//picker 使用
overwrite.picker({
    content: "选择排序",
    init: this.data.sortIndex,
    data: this.data.sortList,
    bindtap: function(id, index) {
        if (that.data.sort != id) {
            that.setData({
                sortIndex: index,
                current: this.data.sortList[index].text
            });
        }
    },
    bindcancel: function() {
        console.log(&#39;cancel&#39;)
    }
});
//alert
overwrite.alert({
    content: &#39;弹框对话框,参数配置详见文档说明&#39;,
    cancelText: &#39;取消&#39;,
    bindconfirm: function() {
        console.log(&#39;确定&#39;);
    },
    bindcancel: function() {
        console.log(&#39;取消&#39;);
    }
});

  • #獨立頁面元件

獨立頁面元件其實就是一個完整的頁面單元(js、wxml、wxss組成),使用很簡單,透過引入相關js方法,呼叫開啟元件即可(可傳遞callback用於資料交換處理)。 --其實作原理是元件提供的js方法將會開啟一個新頁面(api.Navigate.go),並透過註冊事件的形式互動行為資料

[AppleScript] 純文字檢視複製程式碼

//index.js
var dirname = &#39;pages/externalComponent&#39;,
    overwrite = require(&#39;../../utils/overwrite.js&#39;);
require(&#39;../../utils/dateFormat.js&#39;);

(function(require, Page) {
    //获取应用实例
    var app = getApp();
    var CalendarPlugin = require(&#39;components/calendar/index&#39;);
    Page({
        data: {
            date: {
                indate: new Date().format(&#39;yyyy-MM-dd&#39;),
                outdate: new Date(+new Date + 3600000 * 24).format(&#39;yyyy-MM-dd&#39;)
            }
        },
        openCalendar: function() {
            var that = this;
            CalendarPlugin({
                begin: that.data.date.indate,
                end: that.data.date.outdate
            }, function(res) {
                that.data.date.indate = res.start.format(&#39;yyyy-MM-dd&#39;);
                that.data.date.outdate = res.end.format(&#39;yyyy-MM-dd&#39;);
                that.setData({
                    date: that.data.date
                })
            })
        },
        onLoad: function(data) {

        }
    })
})(overwrite.require(require, dirname), overwrite.Page);
  • 頁面層級元件

框架重写Page构造器,支持构建页面时配置一个或多个页面级组件,所谓页面级组件就是该组件的注册形式和页面一致(支持data数据,onLoad、onReady、onShow生命周期事件,fireEvent、showLoading等页面级方法),其实现原理是将组件的所有成员方法和成员属性和依附页面进行合并,并解决了重名冲突,使用者不用关系处理细节,只管像注册一个页面一样注册组件。--需要注意的是页面级别组件不可再次使用Page构造方法。

1、引入组件表现层结构

[AppleScript] 纯文本查看 复制代码

<!--index.wxml-->
<view class="container">
    <view class="userinfo">
        <!--当前页面数据-->
    </view>
    <!--引入组件页面结构-->
    <include src="../../components/base.wxml" />
</view>

2、引入组件样式表

[AppleScript] 纯文本查看 复制代码

/**引入组件样式表**/
@import "filter/index.wxss";
page { background: #f4f4f4; }

3、注册页面时注入组件

[AppleScript] 纯文本查看 复制代码

/**
 * 集成组件dome
 */
var dirname = &#39;pages/internalComponent&#39;,
    overwrite = require(&#39;../../utils/overwrite.js&#39;);
(function(require, Page) {
    /*引入组件js*/
    var filter = require(&#39;./filter/index&#39;);
    Page({
        /**
         * 默认数据
         * @type {Object}
         */
        data: {...},
        onLoad: function(options) {},
    }, [{//注入组件
        component: filter,
        instanceName: &#39;typeFilter&#39;,
        props: {
            style: { top: &#39;44px&#39; }
        },
        events: {
            onChange: &#39;filterChangedCallBack&#39;,
            onOpen: &#39;filterOpenedCallBack&#39;,
            onClose: &#39;filterClosedCallBack&#39;
        }
    }, {
        component: filter,
        instanceName: &#39;categoryFilter&#39;,
        props: {
            style: { top: &#39;44px&#39; }
        },
        events: {
            onChange: &#39;filterChangedCallBack&#39;,
            onOpen: &#39;filterOpenedCallBack&#39;,
            onClose: &#39;filterClosedCallBack&#39;
        }
    }])
})(overwrite.require(require, dirname), overwrite.Page)页面级组件由*.js、*.wxml、*.wxss组成,分别由注册页面引入,其中js部分不可再次使用Page构造
[AppleScript] 纯文本查看 复制代码
├── index.js
├── index.wxml
└── index.wxss[AppleScript] 纯文本查看 复制代码
//页面级组件js声明
/**
 * 筛选器
 */
var dirname = &#39;pages/internalComponent/filter&#39;,
    api = require(&#39;../../../utils/api.js&#39;)(dirname)

var bgAnimation = api.createAnimation({
        duration: 200
    }),
    contentAnimation = api.createAnimation({
        duration: 200
    });

module.exports = {
    data: {
        items: [],
        selectedId: &#39;&#39;,
        bgAnimation: {},
        contentAnimation: {},
        isOpen: false
    },

    /**
     * 监听组件加载
     * @param  {Object} props
     */
    onLoad: function(props) {
        this.setData({
            style: props.style
        })
    },

    /**
     * 初始化
     * @param  {Array} items
     * @param  {String | Number} selectedIndex
     */
    init: function(items, selectedIndex) {},

    /**
     * 选中
     * @param  {Object} e
     */
    select: function(e) {
    }
}

以上是藝龍微信小程式框架元件實例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器