Project introduction

The author has developed more than a year of small procedures, in the process of development has met a lot of pit and inconvenient, clinging to the native development has a certain again at the same time, but to become accustomed to this I use spoil the vue, underlying some of the small program writing really let a person feel uncomfortable, I think everyone in the native development will be faced with some inconvenient, For example, WXSS does not support nesting, does not support variables, mixing, functions, does not support bidirectional binding and so on. And so on not to give up the native development and solve some problems in the development, a native WeChat small application development support frame LWX arises at the historic moment, hope can help you to solve the pain points and inconvenient in some development also take this opportunity to share some of my small application development experience, at the same time, please communicate with perfect this project, Make native applets more silky.

The project address

Github.com/lvyueyang/l…

Project characteristics

  1. It only takes a few minutes to get started quickly, and LWX is like a game aid to help you get through wechat applets quickly

  2. Source code can be directly isolated and quickly incorporated into existing projects

  3. The entire project is less than 100K code, will not affect the size of the project

  4. With the document, the source code is easy to understand, can be customized quickly

Project start

  1. Install gulp globally

    cnpm i -g gulp
    Copy the code
  2. Install dependencies

    cnpm i
    Copy the code
  3. Start real-time compilation of SASS

    gulp serve
    Copy the code
  4. Compile all sass immediately

    gulp all
    Copy the code
  5. Create a new page

    Gulp create-name =< page name >Copy the code
  6. Use wechat developer tools to open the APP folder and start development

Sass is related to WXSS

Sass compilation

  1. The default is only compiled inapp/style/Subfile under,app/style/modulesThe file under will not compile.
  2. inapp/pages/The compiled SCSS file is stored in the same directory. If a new compiled file is added, it must be stored in gulpfile.jswatch_filesAdd directories to array.
  3. To reduce the compiled volume, the WXSS file can be imported directly into the SCSS file (must be added*.wxssSuffix), WXSS compilation is automatically ignored at compile time and references are displayed directly in WXSS.

Such as:

@import ".. /.. /style/modules/color";
@import ".. /.. /style/animation.wxss";

.list {
    padding: 10PX;

    .item {
        padding: 20px; }}Copy the code

Compile as follows:

@import ".. /.. /style/animation.wxss";

.list {
   padding: 10PX; 
}
.list .item {
   padding: 20rpx; 
}
Copy the code

Global style

SCSS icon. SCSS button.scss are imported globally by default. If you don’t need them, you can delete the references in app/app.wxss.

A brief description of the three styles follows

rest.scss

  1. All labels are setbox-sizing: border-box;(As for why not use * you can see for yourself)
  2. Flex layout shorthand style, TAB style, link-list style, form-wrap please check the source code

icon.scss

Here is an example of how to introduce the font icon, because the applet does not support local path, all font files into base64 after reference can be.

Take iconfont as an example to open the generated connection in the browser. Only the base64 string is imported under @font-face

button.scss

The.btn class is used to beautify the button button in a similar way to bootstrap

Here is an overview, please check the source code for details

Global injection

Scenario 1: Bidirectional binding

There are mixins and beforeHook folders in app/hook to implement the bidirectional binding described above and some other globally callable function methods such as:

You would normally write this when adding something like bidirectional binding to an input field

<input type="text" value="{{name}}" bindinput="handlerInput" />
Copy the code
Page({
    data: {
        name: ' '
    },
    onLoad() {
    },
    handlerInput(event) {
        const {value} = event.detail
        this.setData({
            name: value
        })
    }
})

Copy the code

This is fine if the whole project has only one or a few, but if many pages need it then you need to write a lot of handlerInput methods and that can be a lot of work. But in LWX you don’t need to write handlerInput in JS anymore. LWX uses function intercepts to inject a $MixinVModel method for each Page and Component. You only need to do this in WXML, not js.

<input type="text" value="{{name}}" data-model="name" bindinput="$MixinVModel" />
Copy the code

Simply add a data-model attribute to the input, corresponding to the value in data, and replace handlerInput with $MixinVModel.

It also supports binding objects, as shown in the following example

<input type="text" value="{{form.name}}" data-model="form.name" bindinput="$MixinVModel" />
Copy the code

The $MixinVModel also supports the following form components

  1. checkbox-group
  2. radio-group
  3. picker
  4. picker-view
  5. slider
  6. switch
  7. textarea
  8. input

LWX built in other similar $MixinVModel method at the same time You can be in/app/hook/mixins/global view in js, if need to extend can also in here to add modification

mixins API

$MixinVModel

Input box bidirectional binding

Label Attribute Name: data-model Value in data (similar to V-model) This parameter is mandatory

$MixinDownHttpImage

Download network pictures

Tag Attribute Name: data-URL Image address This parameter is mandatory

$MixinCopyText

Copy the words

Label Attribute Name: data-text Indicates the text to be copied. This parameter is mandatory

$MixinToTell

Make a phone call

Tag Attribute Name: data-tell Phone number This parameter is mandatory

$MixinScrollToSelector

Jump to the selector position

Tag Attribute Name: data-selector Selector This parameter is mandatory

$MixinBackTop

Return to the top

Scenario 2: Each page performs the same method at initialization

This scenario is a problem I encountered during the development of the company’s project. The leader wanted to configure the sharing language and sharing image for each page in real time through the backend. The backend provides an interface to obtain the corresponding sharing language and sharing image through the page route.

import api from '.. /.. /api/index'

let shareData = {}
Page({
    data: {},
    onLoad() {
        this.setShareMessage()
    },
    async setShareMessage() {
        try {
            const data = await api.get(this.route)
            shareData = {
                title: data.title,
                path: data.path,
                imageUrl: data.imageUrl,
            }
        } catch (e) {
            console.error(e)
        }
    },
    onShareAppMessage() {
        return shareData
    }
})
Copy the code

As shown above, this is setting information for one page, what if all of them need to be set? One by one? It’s too much work.

In LWX you can do this (similar to the route navigation guard in VUe-Router) :

Create setshare.js in app/hook/beforeHook

import api from '.. /.. /api/index'

// Set the shared language for the server configuration
// this is this for each Page
export default async function () {
    try {
        const data = await api.get(this.route)
        this.onShareAppMessage = function () {
            return {
                title: data.title,
                path: data.path,
                imageUrl: data.imageUrl,
            }
        }
    } catch (e) {
    }
}
Copy the code

Then reference setshare.js in app/hook/index.js

. import setSharefrom './beforeHook/setShare'. const hookOption = { ... onLoad(option) { setShare.call(this)},... }Copy the code

This requirement can be addressed in **LWX ** as described above, and can be extended as you wish.

This example already exists in the source code, which you can view directly

Interacting with pages in web-View (continuous improvement)

Due to the size limitation and release review mechanism of applets, sometimes we need to embed H5 pages to cope with or reuse some scenarios.

LWX provides a solution for applets and H5 to call and interact with each other:

The H5 page is displayed

There is a toWeb method in app/util/toWeb. You only need to pass in the corresponding parameters to jump directly to the corresponding H5 page.

How to set the page share language in H5

After the INTRODUCTION of the WX-SDK and initialization is complete

Perform the following operations in H5

function postShareData() {
    const shareData = {
        title: 'This is the share page'.path: ' '.pathType: 'miniPath'.// When set to miniPath, path is the path address of the applet. Will share the path address in the applet, do not fill path can be set to H5 address
        imageUrl: ' '
    }
	wx.miniProgram.postMessage({data: {shareData}})
}
Copy the code

Authorization component

To reduce duplication of the book bind method LWX in WXML the l-Auth authorization component is provided using the following steps

This component is registered globally and can be referenced directly

  1. The introduction of the component
<l-auth id="Auth"></l-auth>
Copy the code
  1. Using a JS call (for example, to get a phone number)
const auth = this.selectComponent('#Auth')

auth.show({
    openType: 'getPhoneNumber'.content: ' '.subtitle: ' '.mask: ' '.confirmText: ' '.cancelText: ' '.showCancel: ' '.success: res= > {
        console.log(res)
    },
    fail: e= > {
        console.error(e)
    }
})
Copy the code
  1. Argument parsing
code The name of the mandatory The default type note
openType The type of authorization invoked String The correspondingbuttontheopenTypeSupport only [getPhoneNumber.getUserInfo]
content Popup the contents of the modal box no String
subtitle Popup the child content of the modal box no String
mask Click on the mask layer to allow closure no false Boolean
confirmText Confirm button text no determine String
cancelText Cancel button text no cancel String
showCancel Whether to display the cancel button no false Boolean
success Authorized a successful callback Function
fail Callback for authorization failure Function

Customize header components

NavigationStyle = “custom” navigationStyle = “custom”

This component is registered globally and can be referenced directly

<l-header></l-header>
Copy the code

This component only provides adaptation implementation. You can customize other customized attributes based on your own services

Modal components

A custom Modal component is provided within LWX for L-Auth and can also be used for direct references

This component is registered globally and can be referenced directly

<l-modal></l-modal>
Copy the code

attribute

code The name of the mandatory type The default
show Show hidden no Boolean false
headerHide Whether to hide the head no Boolean false
title The title no String
backgroundOpacity Mask layer transparency no String 0.4
mask Click to see if the mask layer is closed no Boolean false
closeIcon Whether the close button is displayed no Boolean true

other

  1. LWX injects $IPx into the Component data of each Page to determine whether it is ipX series bang-lined mobile phone, so as to facilitate the adaptation of IPX series bang-lined mobile phone

  2. Built-in Day.js is a lightweight JavaScript library that handles times and dates, keeping exactly the same API design as moment.js,

    The document address

  3. There are four built-in canvas-related methods in the util folder, which should be useful if you only make posters

The last

Thank you for reading and using LWX. If you have any suggestions or ideas on LWX improvement, please contact me (QQ: 975794403) to communicate and improve LWX together