前端技術前沿2

wx.showToast({
  title: '成功',
  icon: 'success',
  duration: 2000
})
wx.showModal({
  title: '提示',
  content: '這是一個模態彈窗',
  success: function(res) {
    if (res.confirm) {
      console.log('用戶點擊肯定')
    } else if (res.cancel) {
      console.log('用戶點擊取消')
    }
  }
})
<template lang="wxml">
    
    <view class="ui-toast  {{ className }}" hidden="{{ !visible }}">
        <view class="ui-toast_bd">
            <icon wx:if="{{ options.icon}}" type="{{ options.icon }}" size="40" color="{{ options.color }}" class="ui-toast_icon" />
            <view class="ui-toast_text">{{ options.text }}</view>
        </view>
    </view>
</template>

<script>
    import wepy from 'wepy';
    const __timer__ =1900;
    class Toast extends wepy.component {
            
        /**
         * 默認數據
         */
        data={
             list:[
                {
                    type: `success`,
                    icon: `success`,
                    className: `ui-toast-success`,
                },
                {
                    type: `cancel`,
                    icon: `cancel`,
                    className: `ui-toast-cancel`,
                },
                {
                    type: `forbidden`,
                    icon: `warn`,
                    className: `ui-toast-forbidden`,
                },
                {
                    type: `text`,
                    icon: ``,
                    className: `ui-toast-text`,
                },
            ],
            timer:null,
            scope: `$ui.toast`, 
            animateCss:'animateCss',
            className:'',
            visible:!1,
            options:{
                type: ``, 
                timer: __timer__, 
                color: `#fff`, 
                text: `已完成`, 
            }
        }
        /**
         * 默認參數
         */
        __setDefaults__() {
            return {
                type: `success`, 
                timer: __timer__, 
                color: `#fff`, 
                text: `已完成`, 
                success() {}, 
            }
        }
        /**
         * 設置元素顯示
         */
        __setVisible__(className = `ui-animate-fade-in`) {
            this.className = `${this.animateCss} ${className}`;
            this.visible = !0;
            this.$apply();
        }

        /**
         * 設置元素隱藏
         */
        __setHidden__(className = `ui-animate-fade-out`, timer = 300) {
            this.className = `${this.animateCss} ${className}`;
            this.$apply();
            setTimeout(() => {
                this.visible = !1;
                this.$apply();
            }, timer)
        }
        /**
         * @param {Object} opts 配置項
         * @param {String} opts.type 提示類型
         * @param {Number} opts.timer 提示延遲時間
         * @param {String} opts.color 圖標顏色
         * @param {String} opts.text 提示文本
         * @param {Function} opts.success 關閉後的回調函數
         */
        __show__(opts = {}) {
            let options = Object.assign({}, this.__setDefaults__(), opts)
            const TOAST_TYPES = this.list;
            TOAST_TYPES.forEach((value, key) => {
                if (value.type === opts.type) {
                    options.icon = value.icon;
                    options.className = value.className
                }
            })
            this.options = options;
            if(!this.options.text){
                return ;
            };
            clearTimeout(this.timer);
            this.__setVisible__();
            this.$apply();
            this.timer = setTimeout(() => {
                this.__setHidden__()
                options.success&&options.success();
            }, options.timer);

        }
        __info__(args=[]){
            let [ message, callback, duration ]  = args;
            this.__show__({
                type: 'text',
                timer: (duration||__timer__),
                color: '#fff',
                text: message,
                success: () => {callback&&callback()}
            });
        }
        __success__(args=[]){
            let [ message, callback, duration ]  = args;
            this.__show__({
                type: 'success',
                timer: (duration||__timer__),
                color: '#fff',
                text: message,
                success: () => {callback&&callback()}
            });
        }
        __warning__(args){
            let [ message, callback, duration ]  = args;
            this.__show__({
                type: 'forbidden',
                timer: (duration||__timer__),
                color: '#fff',
                text: message,
                success: () => {callback&&callback()}
            });
        }
        __error__(args){
            let [ message, callback, duration ]  = args;
            this.__show__({
                type: 'cancel',
                timer: (duration||__timer__),
                color: '#fff',
                text: message,
                success: () => {callback&&callback()}
            });
        }
        __showLoading__(options){
            wx.showLoading({
                title: (options&&options.title||"加載中"),
            });
        }
        __hideLoading__(){
            wx.hideLoading();
        }
        onLoad(){
            this.$apply()
        }
    }

    export default Toast;
</script>
<template>
    <view class="demo-page">
        <Toast />
        <Modals />
    </view>
</template>

<script>
    import wepy from 'wepy'
    import Toast from '../components/ui/Toast'
    import Modals from '../components/ui/Modals'
    import {fetchJson} from '../utils/fetch';

    export default class Index extends wepy.page {
        config = {
            navigationBarBackgroundColor: "#0ECE8D",
      navigationBarTextStyle:"white",
            navigationBarTitleText: ''
        }
        components = {
            Toast: Toast,
            Modals: Modals
        }
        methods = {
            tapToast(){
                this.$invoke("Toast","__success__",[`提交成功`]);
            }   
        }
    }
</script>

image.png

微信審覈經過郵件模板

image.png

https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_10&index=1php

微信小程序WePY開發框架css

npm install -g wepy-cli

// 1.7.0以前
wepy new myproject
// 1.7.0以後
wepy init standard myproject

wepy --version

npm install

npm run dev

wepy build --watch

project.config.json
{
  "description": "A WePY project",
  "setting": {
    "urlCheck": true,
    "es6": false,
    "postcss": false,
    "minified": false,
    "newFeature": true
  },
  "compileType": "miniprogram",
  "appid": "touristappid",
  "projectname": "hellowepy",
  "miniprogramRoot": "./dist",
  "condition": {}
}

es6: 對應關閉ES6轉ES5選項,關閉。 
postcss: 對應關閉上傳代碼時樣式自動補全選項,關閉。 
minified: 對應關閉代碼壓縮上傳選項,關閉。
urlCheck: 對應不檢查安全域名選項,開啓。

wepy.config.js配置文件說明

sass:sass編譯配置,參見這裏。https://github.com/sass/node-sass
less:less編譯配置,參見這裏。http://lesscss.org/#using-less-usage-in-code
postcss:postcss編譯配置,參見這裏。http://www.css88.com/archives/7317
stylus:stylus編譯配置,參見這裏。http://www.zhangxinxu.com/jq/stylus/js.php
babel:babel編譯配置,參見這裏。http://babeljs.io/docs/usage/options/
typescript:typescript編譯配置,參見這裏。https://www.tslang.cn/docs/home.htmlhtml

app小程序實例
import wepy from 'wepy';

export default class MyAPP extends wepy.app {
  customData = {};

  customFunction () {}

  onLaunch () {}

  onShow () {}

  config = {}  // 對應 app.json 文件

  globalData = {}
}

page頁面實例和Component組件實例node

import wepy from 'wepy';

export default class MyPage extends wepy.page {
//export default class MyComponent extends wepy.component {
  customData = {} //自定義數據

  customFunction () {} //自定義方法

  onLoad () {} //在Page和Component共用的生命週期函數

  onShow () {} //只在Page中存在的頁面生命週期函數

  config = {}; //只在Page實例中存在的配置數據,對應於原生的page.json文件

  data = {}; //頁面所需數據均需在這裏聲明,可用於模板數據綁定

  components = {}; //聲明頁面中所引用的組件,或聲明組件中所引用的子組件

  mixins = []; //聲明頁面所引用的Mixin實例

  computed = {}; //聲明計算屬性

  watch = {}; //聲明數據watcher

  methods = {}; //聲明頁面wxml中標籤的事件處理函數。

  events = {}; //聲明組件之間的事件處理函數
}

循環渲染

<template>
    <!-- 注意,使用for屬性,而不是使用wx:for屬性 -->
    <repeat for="{{list}}" key="index" index="index" item="item">
        <!-- 插入<script>腳本部分所聲明的child組件,同時傳入item -->
        <child :item="item"></child>
    </repeat>
</template>

<script>
    import wepy from 'wepy';
    // 引入child組件文件
    import Child from '../components/child';

    export default class Index extends wepy.component {
        components = {
            // 聲明頁面中要使用到的Child組件的ID爲child
            child: Child
        }

        data = {
            list: [{id: 1, title: 'title1'}, {id: 2, title: 'title2'}]
        }
    }
</script>
data = {
  a: 1
}

//計算屬性aPlus,在腳本中可經過this.aPlus來引用,在模板中可經過{{ aPlus }}來插值
computed = {
  aPlus () {
    return this.a + 1
  }
}
data = {
    num: 1
}

watch = {
    num (newValue, oldValue) {
        console.log(`num value: ${oldValue} -> ${newValue}`)
    }
}

onLoad () {
    setInterval(() => {
        this.num++;
        this.$apply();
    }, 1000)
}

props

// parent.wpy

<child :title="parentTitle" :syncTitle.sync="parentTitle" :twoWayTitle="parentTitle"></child>

data = {
    parentTitle: 'p-title'
};


// child.wpy

props = {
    // 靜態傳值
    title: String,

    // 父向子單向動態傳值
    syncTitle: {
        type: String,
        default: 'null'
    },

    twoWayTitle: {
        type: String,
        default: 'nothing',
        twoWay: true
    }
};

onLoad () {
    console.log(this.title); // p-title
    console.log(this.syncTitle); // p-title
    console.log(this.twoWayTitle); // p-title

    this.title = 'c-title';
    console.log(this.$parent.parentTitle); // p-title.
    this.twoWayTitle = 'two-way-title';
    this.$apply();
    console.log(this.$parent.parentTitle); // two-way-title.  --- twoWay爲true時,子組件props中的屬性值改變時,會同時改變父組件對應的值
    this.$parent.parentTitle = 'p-title-changed';
    this.$parent.$apply();
    console.log(this.title); // 'c-title';
    console.log(this.syncTitle); // 'p-title-changed' --- 有.sync修飾符的props屬性值,當在父組件中改變時,會同時改變子組件對應的值。
}
import wepy from 'wepy'
export default class Com extends wepy.component {
    components = {};
    data = {};
    methods = {};
    events = {
        'some-event': (p1, p2, p3, $event) => {
               console.log(`${this.$name} receive ${$event.name} from ${$event.source.$name}`);
        }
    };
}
Page_Index中調用組件ComA的某個方法
this.$invoke('ComA', 'someMethod', 'someArgs');

組件ComA中調用組件ComG的某個方法
this.$invoke('./../ComB/ComG', 'someMethod', 'someArgs');

slot 組件插槽git

<view class="panel">
    <slot name="title">默認標題</slot>
    <slot name="content">默認內容</slot>
</view>

<panel>
    <view slot="title">新的標題</view>
    <view slot="content">
        <text>新的內容</text>
    </view>
</panel>
<!-- 推薦用法 --->
// list.wpy
<repeat for="{{mylist}}">
    <view>{{item.name}}</view>
</repeat>

// index.wpy
<List :mylist.sync="mylist"></List>

// 原生的事件傳參方式:
<view data-id="{{index}}" data-title="wepy" data-other="otherparams" bindtap="tapName"> Click me! </view>

Page({
    tapName: function (event) {
        console.log(event.currentTarget.dataset.id)// output: 1
        console.log(event.currentTarget.dataset.title)// output: wepy
        console.log(event.currentTarget.dataset.other)// output: otherparams
    }
});

// WePY 1.1.8之後的版本,只容許傳string。
<view @tap="tapName({{index}}, 'wepy', 'otherparams')"> Click me! </view>

methods: {
    tapName (id, title, other, event) {
        console.log(id, title, other)// output: 1, wepy, otherparams
    }
}

// 原生代碼:
wx.request({
    url: 'xxx',
    success: function (data) {
        console.log(data);
    }
});

// WePY使用方式, 須要開啓Promise支持
wepy.request('xxxx').then((d) => console.log(d));

// async/await的使用方式, 須要開啓Promise和async/await支持
async function request () {
   let d = await wepy.request('xxxxx');
   console.log(d);
}
import wepy from 'wepy';

export default class extends wepy.app {
    constructor () {
        // this is not allowed before super()
        super();
        // 攔截request請求
        this.intercept('request', {
            // 發出請求時的回調函數
            config (p) {
                // 對全部request請求中的OBJECT參數對象統一附加時間戳屬性
                p.timestamp = +new Date();
                console.log('config request: ', p);
                // 必須返回OBJECT參數對象,不然沒法發送請求到服務端
                return p;
            },

            // 請求成功後的回調函數
            success (p) {
                // 能夠在這裏對收到的響應數據對象進行加工處理
                console.log('request success: ', p);
                // 必須返回響應數據對象,不然後續沒法對響應數據進行處理
                return p;
            },

            //請求失敗後的回調函數
            fail (p) {
                console.log('request fail: ', p);
                // 必須返回響應數據對象,不然後續沒法對響應數據進行處理
                return p;
            },

            // 請求完成時的回調函數(請求成功或失敗都會被執行)
            complete (p) {
                console.log('request complete: ', p);
            }
        });
    }
}

請點贊!由於你的鼓勵是我寫做的最大動力!

官方微信公衆號

吹逼交流羣:711613774es6

吹逼交流羣

相關文章
相關標籤/搜索