Front end technology frontier 2

wx.showToast({
  title: 'Success',
  icon: 'success',
  duration: 2000
})
wx.showModal({
  title: 'Tips',
  content: 'This is a modal pop-up window',
  success: function(res) {
    if (res.confirm) {
      console.log('User click OK')
    } else if (res.cancel) {
      console.log('User click Cancel')
    }
  }
})
<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 {
            
        /**
         * Default data
         */
        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: `Completed`, 
            }
        }
        /**
         * Default parameters
         */
        __setDefaults__() {
            return {
                type: `success`, 
                timer: __timer__, 
                color: `#fff`, 
                text: `Completed`, 
                success() {}, 
            }
        }
        /**
         * Set element display
         */
        __setVisible__(className = `ui-animate-fade-in`) {
            this.className = `${this.animateCss} ${className}`;
            this.visible = !0;
            this.$apply();
        }

        /**
         * Set element hide
         */
        __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 Configuration item
         * @param {String} opts.type Prompt type
         * @param {Number} opts.timer Prompt delay time
         * @param {String} opts.color Icon color
         * @param {String} opts.text Prompt text
         * @param {Function} opts.success Callback function after closing
         */
        __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||"Loading"),
            });
        }
        __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__",[`Submit successfully`]);
            }   
        }
    }
</script>
image.png
Wechat approved email template
image.png

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

Development framework of wechat widget WePY

npm install -g wepy-cli

// Before 1.7.0
wepy new myproject
// After 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: Corresponding closure ES6 turn ES5 Option, turn off. 
postcss: Close the option of automatic completion of style when uploading code. 
minified: Turn off the code compression upload option.
urlCheck: Do not check the security domain name option.

wepy.config.js Profile description

Sass: sass compilation configuration, see here. https://github.com/sass/node-sass
Less: for less compilation configuration, see here. http://lesscss.org/#using-less-usage-in-code
Postcss: postcss compilation configuration, see here. http://www.css88.com/archives/7317
Stylus: stylus compilation configuration, see here. http://www.zhangxinxu.com/jq/stylus/js.php
babel: babel compilation configuration, see here. http://babeljs.io/docs/usage/options/
Typescript: typescript compilation configuration, see here. https://www.tslang.cn/docs/home.html

app Applet instance
import wepy from 'wepy';

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

  customFunction () {}

  onLaunch () {}

  onShow () {}

  config = {}  // Corresponding to app.json file

  globalData = {}
}

Page page instance and Component component instance

import wepy from 'wepy';

export default class MyPage extends wepy.page {
//export default class MyComponent extends wepy.component {
  customData = {} //Custom data

  customFunction () {} //Custom method

  onLoad () {} //Life cycle functions shared by Page and Component

  onShow () {} //Page lifecycle functions that only exist in page

  config = {}; //The configuration data that only exists in the Page instance corresponds to the native page.json file

  data = {}; //The data required by the page should be declared here, which can be used for template data binding

  components = {}; //Declare a component referenced in a page, or a subcomponent referenced in a component

  mixins = []; //Declare the Mixin instance referenced by the page

  computed = {}; //Declare calculated properties

  watch = {}; //Declare data watcher

  methods = {}; //Declare the event handler for the tag in the page wxml.

  events = {}; //Declare event handlers between components
}

Circular rendering

<template>
    <!-- Note, use for Property instead of using wx:for attribute -->
    <repeat for="{{list}}" key="index" index="index" item="item">
        <!-- insert<script>The child Components, passing in at the same time item -->
        <child :item="item"></child>
    </repeat>
</template>

<script>
    import wepy from 'wepy';
    // Import child component file
    import Child from '../components/child';

    export default class Index extends wepy.component {
        components = {
            // The ID of the child component to be used in the declaration page is child
            child: Child
        }

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

//Calculate the attribute aPlus, which can be referenced by this.aPlus in the script and interpolated by {{aPlus}} in the template
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 = {
    // Static passing value
    title: String,

    // One way dynamic value transfer from parent to child
    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. -- when twoway is true, when the attribute value in the child component props changes, the corresponding value of the parent component will be changed at the same time
    this.$parent.parentTitle = 'p-title-changed';
    this.$parent.$apply();
    console.log(this.title); // 'c-title';
    console.log(this.syncTitle); // 'p-title-changed' -- props attribute value with. sync modifier. When it is changed in the parent component, the corresponding value of the child component will be changed at the same time.
}
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}`);
        }
    };
}
A way to invoke component ComA in Page_Index
this.$invoke('ComA', 'someMethod', 'someArgs');

A way to invoke component ComG in component ComA
this.$invoke('./../ComB/ComG', 'someMethod', 'someArgs');

Slot component slot

<view class="panel">
    <slot name="title">Default title</slot>
    <slot name="content">Default content</slot>
</view>

<panel>
    <view slot="title">New title</view>
    <view slot="content">
        <text>New content</text>
    </view>
</panel>
<!-- Recommended usage --->
// list.wpy
<repeat for="{{mylist}}">
    <view>{{item.name}}</view>
</repeat>

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

// Native event parameter passing method:
<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
    }
});

// For versions after WePY 1.1.8, only string can be passed.
<view @tap="tapName({{index}}, 'wepy', 'otherparams')"> Click me! </view>

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

// Native code:
wx.request({
    url: 'xxx',
    success: function (data) {
        console.log(data);
    }
});

// Use of WePY requires Promise support
wepy.request('xxxx').then((d) => console.log(d));

// To use async/await, you need to enable Promise and async/await support
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();
        // Intercept request request
        this.intercept('request', {
            // Callback function on request
            config (p) {
                // Attach time stamp attribute uniformly to OBJECT parameter OBJECT in all request requests
                p.timestamp = +new Date();
                console.log('config request: ', p);
                // The OBJECT parameter OBJECT must be returned, otherwise the request cannot be sent to the server
                return p;
            },

            // Callback function after successful request
            success (p) {
                // The received response data object can be processed here
                console.log('request success: ', p);
                // The response data object must be returned, otherwise the response data cannot be processed later
                return p;
            },

            //Callback function after request failure
            fail (p) {
                console.log('request fail: ', p);
                // The response data object must be returned, otherwise the response data cannot be processed later
                return p;
            },

            // Callback function when the request is completed (both success and failure of the request will be executed)
            complete (p) {
                console.log('request complete: ', p);
            }
        });
    }
}

Please praise! Because your encouragement is the biggest driving force of my writing!

Official WeChat public address

Forced communication group: 711613774

Push communication group

Tags: Attribute sass npm JSON

Posted on Fri, 08 Nov 2019 06:51:31 -0800 by sssphp