Development of small procedures for so long, sorted out a list of some skills to share.

1. The backgroundColor configuration is invalid

BackgroundColor can be used to set the color of the window:

{
  "backgroundColor": "#f2f2f2"
}
Copy the code

After setting so found a little effect, carefully study, the original window color refers to the bottom layer. (Oh my God!)

The solution is as simple as using the Page selector:

page {
  background: #f2f2f2;
}
Copy the code

Page is the root node of the page, which is HTML in H5, so you can use it to set some styles.

2. Change the custom component root node style

The header component code is as follows:

<view class="header">
  header
</view>
Copy the code

You can see that there are additional header nodes after rendering.

Component nodes are not useful in most development scenarios, but in some cases they can affect style, such as elastic layouts. I won’t post a demo here, but this technique will definitely be used, just check it out.

We can modify the component node in the custom component style file using the :host selector:

:host {
  padding: 50px;
}
Copy the code

Compare this to the box model above

3. What is a block tag

Block tags are similar to the Fragment in React and template in Vue.

React /vue doesn’t matter if you haven’t seen react/vue before.

<block>
  <view>say</view>
  <view>hello</view>
</block>
Copy the code

After rendering, the block node disappears

<view>say</view>
<view>hello</view>
Copy the code

If there is no block node, do this:

<! -- More render with node tags -->
<view>
  <view>say</view>
  <view>hello</view>
</view>
Copy the code

More commonly used with wx:if

<block wx:if="{{ show }}">
  <view wx:for="{{ arr }}" wx:key="index">{{ item }}</view>
</block>
Copy the code

4. How to set the background picture

It’s hard to get a background picture.

Usually in H5 set the background picture directly into the address

background: url("/example.png");
Copy the code

But in the small program unexpectedly can not…

Why??

Small program: you can only obediently introduce network picture xx: MMP, set up a picture to make so many tricks? I think... Small program: I don't want you to feel, I want me to feel.Copy the code

Xx. We have to go through the back door.

1. You can convert the picture tobase64You can:

background-image: url("data:image/svg+xml; base64,PHN2ZyBjbGFzcz0ibGRzLXNwaW5uZXIiIHdpZHRoPSIxMDlweCIgIGhlaWdodD0iMTA5cHgiICB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwM C9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgcHJlc2V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png)">
</view>
Copy the code

This method I should not say ~ because in the real machine will not work… (No tears)

3. Using the image method, I will not paste the demo in detail, but just use image to change the style to the bottom.

<view>
  <image src="example.png" />
</view>
Copy the code

Finally: the use of local images for projects is very rare, and I’ve only seen a few of them anyway. So the easiest way to set a background image is to use Base64.

5. Object-fit is invalid

Object-fit feature is very much used in H5. It can keep a certain proportion of the picture without distortion. If you want to know its specific content to MDN

Using this feature on images in applets has no effect

.image {
  object-fit: cover;
}
Copy the code

It is also easy to solve this problem by using the attributes that come with the applet

<image src="example.png" mode="aspectFill"></image>
Copy the code

You can view the mode properties in the official list

Mock data

In WEB development, we use MockJS to intercept requests to simulate data.

Can it also be used in applets? Of course it is, except for the small program wx.request.

1. Install MockJS

npm i mockjs
Copy the code

2. Create wxmock.js

// If you have some skills, you can understand it
// the underlying API of wechat cannot be rewritten, so use defineProperty to make it writable
// Rewrite the underlying wx.request method and do something about it

const __request = wx.request;
const Mock = require('mockjs');

Object.defineProperty(wx, 'request', { writable: true });

wx.request = function (config) {
  if (typeof Mock._mocked[config.url] === 'undefined') {
    __request(config);
    return;
  }

  const resTemplate = Mock._mocked[config.url].template;
  const response = Mock.mock(resTemplate);

  if (typeof config.success === 'function') {
    config.success(response)
  }
  
  if (typeof config.complete === 'function') {
    config.complete(response)
  }
};

module.exports = Mock;
Copy the code

3. Use wxmock.js

const Mock = require('wxMock.js') // Use Mock as usual. Mock ('/api/example', { data: { ... }})Copy the code

4. Introduce mocks in the app.js entry file

import "./mock/index.js";
Copy the code

7. The picture width is 100%, and the height cannot be self-adapted

The height is adaptive in WEB development when the image is set to 100%.

Little programs just don’t work, don’t work.

Since the bottom layer of the applet has already added width and height to the image, the default is 240px.

The solution is to add a mode attribute to the image element

<image src="example.png" mode="widthFix"></image>
Copy the code

When you add this mode and set the image to 100% width, the applet automatically calculates its height and makes the image self-adaptive.

Can you define multiple types of properties?

I have to say yes first.

This feature is new to the Applets foundation library 2.6.5.

The optionalTypes field is an array that specifies the property type, and can be multiple.

Component({
  properties: {
    lastLeaf: {
      // This attribute can be one of three types: Number, String, or Object
      type: Number.optionalTypes: [String.Object].value: 0}}})Copy the code

9. Jumping to Tabbar does not return to the previous level

This is a problem I suspect every developer has experienced.

Switching from regular pages to tabbar pages can only be done using wx.switchTab. This API has a problem with jumping to a Tabbar page and closing all other non-Tabbar pages

So when you jump to the top left corner of the Tabbar page, the back button is gone, so you can’t go back to the previous level.

The most commonly used scenario is the shopping cart. A page can not be returned to the previous level when jumping to the shopping cart. That experience is not very bad.

This problem I will not paste demo, say its scheme.

  • Custom navigation header, add a back key
  • Custom tabbar component, this time there is no switchTab jump
  • Package the shopping cart page as a component, and then create two new pages, one for tabbar and one for regular pages, which JD currently uses.

10. Page usagebehaviors

Behaviors are features used to share code between components, similar to “mixins” or “traits” in some programming languages.

Unfortunately, Behaviors only work on components. What if you want to use them on a page?

While you can’t use behaviors on a page, you can simulate mixins.

First, you can use the LoDash utility class merge

Or implement it yourself:

export function merge(source, other) {
  if(! isObject(source) || ! isObject(other)) {return other === undefined ? source : other
  }
  // Merge the keys of two objects, in addition to distinguish array initial value is []
  return Object.keys({ ... source, ... other }).reduce((acc, key) = > {
    // merge values recursively
    acc[key] = merge(source[key], other[key])
    return acc
  }, Array.isArray(source) ? [] : {})}Copy the code

Say.js uses mixins and exports them as a normal object

export default {
  data: {
    say: 'hello'
  },
  $setData() {
    this.setData({ say: 'world'}}})Copy the code

3. Introduce mixins into your page

import merge from './merge.js'
import say from 'say.js'

Page(merge(say, {
  data: {
    foo: 'foo'
  },
  onLoad() {
    // Call methods in mixins
    this.$setData()
  }
}))
Copy the code

This is a perfect mixins solution, but it has a drawback: the later function overwrites the previous one, so you can solve this problem in the lifecycle:

// say.js mixins
export default {
  onLoad(options) {
    this.onLoadCallback && this.onLoadCallback(options)
  }
}
Copy the code

This can be changed slightly on pages that use mixins

// ...

Page(merge(say, {
  onLoadCallback(options) {
    // ... do something}}))Copy the code

11, avoidthirdScriptErrorabnormal

Throwing thirdScriptError causes the entire application to crash and go blank.

  • 1. Do not include it in appletsdom/bomThe related API, even if not used, will throw an exception because the applet will compile the entire project.
  • 2,propertiesBe sure to declare the type
  • 3, do not reference in advance, such as App is not registered to callgetApp

conclusion

There are some differences between wechat small program development and the Web. Although the development flexibility of small program is not so high now, it will slowly be improved with continuous iteration and update, and is favored by many developers.

This article won’t stop there, as long as some good tips are summed up and shared.