Dry Share: applet project practices and lessons learned

Recent contact with a small program development, and I especially would this development process used to summarize the relevant knowledge, as the accumulation of experience. I hope for their future development, to provide some help, while increasing the ability to solve problems. If wrong, please correct me.

github address ; project address ;

weui: the use of micro-channel native visual experience Style Library

Understanding: WeUI is consistent with a micro-channel native visual experience base style library, the official micro-channel design team tailored to micro letter pages and micro letter applets, so the user's perception of a more unified.

Official website: https://weui.io/

github Address: https://github.com/weui/weui-wxss

Launched a micro-channel official style library, to facilitate the development, for some similar UI interface we need to introduce without the need of repeat-create the wheel. We just need to import weui.wxss and so can reduce the amount of css layout work.

Pictures on local resource path (background)

Applet tag supports local picture only image resource path, wxss in the background-image is not supported.
If you want to use a background image in css, the solution:

1, the image is converted into the local line address base64 paths. Conversion of address lines base64: http://imgbase64.duoshitong.com/

2, url inside the Source must be completed outside the chain. as follows:

area{
   background: url('https://mirror-gold-cdn.xitu.io/168e088859e325b9d85?imageView2/1/w/100/h/100/q/85/format/webp/interlace/1' ) no-repeat center;
}

websocket problem

Experience supports ws protocol, need to open the debug mode
if the domain name is connected websocket non-IP address, you can not connect through a proxy to change the host computer to specify the address socket resolve domain names
if the test environment, it is recommended:

  1. Build a proprietary test environment websocket domain
  2. Direct use of IP addresses to access the test environment websocket

About the time of format processing method in ios

Background: Since only recognizes ios format yyy / mm / dd format, such as "2018-10-31 20:30:00" unrecognized format;
default database to get the date format is "2018-08-30 12:00 : 00 "If you do not replace" - ", then in the IOS it is not by getDate (datestring) to get the date of the object. Android both formats were normal.

Solution: By regular replaced all the "-", as follows:

var dateStr = "2018-09-08 12:30:30"; // 后台返回的时间字符串
dateStr = dateStr.replace(/-/g, '/');
console.log(dateStr); 
结果为:2018/09/08 12:30:30

Applet on DOM subsidiary argument, the function parameter acquisition method

view.wxml:

 // DOM上附属参数
<view 
  data-id='{{fangyuanItem.id}}' 
  data-houseitemid='{{fangyuanItem.houseItemId}}' 
  catchtap='viewMendianDetail'>
</view>

view.js:

  // 函数中获取参数
  page({
      data:{},
      viewMendianDetail: function (e) {
        var roomtypeid = e.currentTarget.dataset.id;
        var houseItemId = e.currentTarget.dataset.houseitemid;
      }
  })

Note: When the subsidiary parameter, data-key, key format lowercase;

Applets can not jump page navigator on tabBar

Method a: navigator to the open-type switchTab

code show as below:

<navigator url="../cart/index" open-type="switchTab">
   <text>首页</text>
</navigator>

Method two: wx.switchTab ({})

code show as below:

index.wxml:

 <text catchtap="toIndex">首页</text>

index.js:

 page({
    toIndex(){
        wx.switchTab({  
          url: '../cart/index'
        }) 
    }
 })

wx.navigateTo mass participation and wx.switchTab navigation

wx.navigateTo navigation parameter passing

1.wx.navigateTo, url parameter splicing parameter passing;

// 访问房型详情
viewMendianDetail: function (e) {
  var roomtypeid = e.currentTarget.dataset.id;
  var houseItemId = e.currentTarget.dataset.houseitemid;
  wx.navigateTo({
    url: '/pages/index/index?houseItemId=' + houseItemId + '&roomtypeid=' + roomtypeid,
  })
}

2. Navigate to the receiving component by the parameter object lifecycle functions onLoad, and the data provided in the present assembly

pages/index/index:

 onLoad: function (options) {
    //console.log(options)
    var houseItemId = options.houseItemId
    var roomtypeid = options.roomtypeid
    this.setData({
        houseItemId: houseItemId,
        roomTypeId: roomtypeid
    })
}

wx.switchTab navigation parameter passing

1. premise: app.js global variables are defined in SearchInfo , as follows:

App({
    globalData: {
        searchInfo:{
          searchInput:"",
          laiyuan:0
        }
  }
});

2. app.globalData global parameters defined as follows:

a.wxml:

const app = getApp()
page({
    data:{},
    toZhaofang:function(e){
        app.globalData.searchInfo = {
          "searchInput": searchInput,
          "laiyuan": 1
        }
        wx.switchTab({
          url: '/pages/tabbar/zhaofang/index',
        })
   }
})

3. By app.globalData receives global parameters, as follows:
zhaofang / index.wxml:

 const app = getApp()
 page({
    onLoad(){ 
       let searchInfo = app.globalData.searchInfo
       let searchInput = searchInfo.searchInput;
    }
 })

Custom applet forwarding

By default, we need to click on the upper right corner of the small program ... to see forward, this does not play a guiding role for the user, the usual practice is to use a button, and open-type setting for the share, so that you can button to start sharing.
But the primary button is difficult to see, we can set up a picture, and adjust the style of the buttons;

The effect is as:

share.wxml:

<button open-type="share"><image src="/images/icon-share.png"></image></button>

share.wxss:

button {
    padding:0;
    width:70rpx;
    height:70rpx;
    display:block;
    border:0;
    background: transparent;
}
button::after {
    border:0; 
}

Note: especially for the button :: after to be set or a button of the border can not be removed.

To obtain phone information (including width, height) by wx.getSystemInfo ()

Applet provided getSystemInfo () method, which can be used to obtain information about the device, such as phone model. Device pixel ratio. Higher screen width, etc. The most commonly used is the width and height of the screen.
In order to ensure the accuracy of the information acquired, wx .getSystemInfoSync when the page is initialized to calculate. So the best way is to use an asynchronous interface, and the function call onReady.

info.js:

Page({
  onReady: function (options) {
    this.getSystemInfo();
  },
  getSystemInfo:function(){
    wx.getSystemInfo({
      success: function (res) {
         console.log("手机屏幕的宽度为:" + res.screenWidth);
         console.log("手机屏幕的高度为:" + res.screenHeight);
        console.log("可视网页的宽度为:" + res.windowWidth);
        console.log("可视网页的高度为:" + res.windowHeight);
        console.log("手机的系统为:" + res.system);
        console.log("微信版本号为:" + res.version);
      }
    })
  }
})

The results are shown:

Template (template) definition of mass participation

Definitions: WXML provide a template (template), you can then call in a different place in the defined template code snippets.
Use the name attribute as the name of the template. Such as:

1. Define the template file
baseTemplate.wxml:

<template name="msgItem">
  <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
  </view>
</template>

2. Use the template data and pass parameters by
using property is, the statement needs to use a template, the template will then pass the required data. As follows:
user.wxml:

<import src="../template/baseTemplate.wxml" />
 <block wx:for="{{goodlist}}" wx:key="idx">
    <template is="msgItem" data="{{...item}}"></template>
</block>

note:

1. data = "{{... item}}" way to pass a parameter, called template, no write Item;

2. If you want to transfer data to multiple templates, separated by commas, item is an object, index is a single data, use the key-value pairs.

<view class="tab-list" wx:for="{{list}}" wx:key="index">
   <template is="day-tab" data="{{item,index:index,target:target}}" wx:key="index"></template>
</view>

user.js , the data format is defined as follows:

page({
   data:{
       goodlist:[
           { index: 0,msg: 'this is a template',time: '2016-06-18'},
           { index: 1,msg: 'this is a template1',time: '2017-06-18'},
           { index: 2,msg: 'this is a template2',time: '2018-06-18'}
       ]
   }
})

City Select Components picker to use

The effect is as:


Introducing :

picker: bounce from the bottom of the scroll selector.

code show as below:

picker.wxml:

<picker  
    mode='selector' 
    range="{{region}}" 
    range-key="{{'cityName'}}" 
    value='{{indexCity}}'
    bindchange="chooseCity" 
    >
    <view class="picker">  
        {{region[indexCity].cityName}}
    </view>  
</picker>

picker.js:

page({
   data:{
       region:[
           {"cityName":"北京市","cityId":"12345"},
           {"cityName":"上海市","cityId":"67890"},
           {"cityName":"武汉市","cityId":"54321"},
       ]
   },
   chooseCity(e){
     var value = e.detail.value;  // index下标
   }
})

Property description :

mode (String): Select type; valid value of mode:

  • selector: Normal selector;
  • multiSelector: multi-column selector;
  • time: time selector;
  • date: the date picker;
  • region: provinces selector

The slide assembly scroll-view

Introduction: Scroll-View: View scrollable area. When using vertical scrolling, a scroll-view requires a fixed height, provided by the height WXSS. The default length of the unit for the component properties px, 2.4.0 supportive incoming units (rpx / px).

Detailed documentation : Please refer to ;

The effect is as:

Use as follows:

<scroll-view scroll-x="true"></scroll-view>

note:

Solution 1.scroll-view of the scroll-x failed

To scroll-view plus white-space: nowrap; the child element at box scroll-view plus display: inline-block can be.

code show as below:

.scroll-box {
   white-space: nowrap;
}
.scroll-box .box{
   display:inline-block
}

2. The text data is displayed by default two rows, with the excess "..." instead of:

Style code is as follows:

line-height: 40rpx;
white-space:pre-line;
display:-webkit-box;
-webkit-box-orient:vertical;
-webkit-line-clamp:2;
overflow:hidden;

Cover-image view of the container and cover-view

Use Background:

In the small micro-channel programs often use some native components, such as map, video, canvas, camera, these primary components want other elements on its cover, or cover-view must cover-image assembly.

cover-view

介绍: 覆盖在原生组件之上的文本视图。可覆盖的原生组件包括 map、video、canvas、camera、live-player、live-pusher。只支持嵌套 cover-view、cover-image,可在 cover-view 中使用 button。组件属性的长度单位默认为px,2.4.0起支持传入单位(rpx/px)。

注意: 只支持基本的定位、布局、文本样式。不支持设置单边的border、background-image、shadow、overflow: visible等。

1、支持background-color,不支持background-image,如果你发现你的素材在真机出不来,而且你又设置了背景图片的话,那你可以把这些元素全部替换成cover-image。

2、不支持overflow: visible也是有点坑,这样的话,你想超出依然显示,就需要设置一个同级元素并提升层级才能达到效果了。

效果如图:

示例代码如下:

video.wxml:

<video id="myVideo" src="http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400" controls="{{false}}" event-model="bubble">
  <cover-view class="controls">
    <cover-view class="play" bindtap="play">
      <cover-image class="img" src="/path/to/icon_play" />
    </cover-view>
    <cover-view class="pause" bindtap="pause">
      <cover-image class="img" src="/path/to/icon_pause" />
    </cover-view>
    <cover-view class="time">00:00</cover-view>
  </cover-view>
</video>

video.wxss:

.controls {
  position: relative;
  top: 50%;
  height: 50px;
  margin-top: -25px;
  display: flex;
}
.play,.pause,.time {
  flex: 1;
  height: 100%;
}
.time {
  text-align: center;
  background-color: rgba(0, 0, 0, .5);
  color: white;
  line-height: 50px;
}
.img {
  width: 40px;
  height: 40px;
  margin: 5px auto;
}

video.js

Page({
  onReady() {
    this.videoCtx = wx.createVideoContext('myVideo')
  },
  play() {
    this.videoCtx.play()
  },
  pause() {
    this.videoCtx.pause()
  }
})

cover-image

介绍: 覆盖在原生组件之上的图片视图,可覆盖的原生组件同cover-view,只支持嵌套在cover-view里。

cover-image发现了两个问题:

1、虽说和image组件基本一样,但是设置mode属性也就是图片裁剪、缩放的模式无效

2、宽度固定,高度auto,时,按照正常效果应该是图片按比例伸缩展示,但是发现该组件高度一直为0,只能根据应用场景寻找其他替代方案了。

视图容器swiper

介绍: 滑块视图容器。其中只可放置swiper-item组件,否则会导致未定义的行为。

效果如图:

代码如下:

swiper.wxml:

<view class="area">
   <view class="fuTitle">swiper</view>
   <view class="intro"> 
      <text class="one-title">介绍:</text>
      <text>滑块视图容器。其中只可放置swiper-item组件,否则会导致未定义的行为。</text>
   </view>
   <view class="item">
      <swiper 
        indicator-dots="{{indicatorDots}}"
        indicator-color="{{indicatorColor}}"
        indicator-active-color="{{indicatorActiveColor}}"
        previous-margin="{{previousMargin}}"
        next-margin="{{nextMargin}}"
        display-multiple-items="{{itemsNum}}"
        autoplay="{{autoplay}}" 
        interval="{{interval}}" 
        duration="{{duration}}"
        bindchange="bindchange"
        easing-function="{{easing}}"
        >
        <block wx:for="{{imgUrls}}" wx:key="{{index}}">
          <swiper-item item-id="{{index}}">
            <image src="{{item}}" class="slide-image" width="355" height="150"/>
          </swiper-item>
        </block>
      </swiper>
   </view>
</view>

swiper.js

Page({
    data: {
         imgUrls:[
           "../../images/bo1.jpg",
           "../../images/bo2.jpg",
           "../../images/bo3.jpg",
           "../../images/bo4.jpg"
         ],
         indicatorDots: true,    // 是否显示滚动圆点图标
        indicatorColor: "#07c160", // 指示点颜色
        indicatorActiveColor: "#28d3ee", // 当前选中的指示点颜色
        previousMargin: "10rpx", // 前边距,可用于露出前一项的一小部分,接受 px 和 rpx 值
        nextMargin: "10rpx",     // 后边距,可用于露出后一项的一小部分,接受 px 和 rpx 值
        itemsNum:1,              // 同时显示的滑块数量
        easing: "default",       // 指定 swiper 切换缓动动画类型
        autoplay: true,         // 是否自动播放
        interval: 5000,         // 自动切换时间间隔
        duration: 1000          // 滑动的动画时长
    }
})

rich-text实现富文本解析

介绍: 富文本。主要用来解析服务端传递过来的富文本html格式的数据,进行展示在页面上。类似于vue的v-html指令;

效果如图:

代码如下:

richText.wxml:

<view class="rich-area">
      <rich-text nodes="{{article_content}}" bindtap="tapRichText"></rich-text>
</view>

richText.js:

Page({
   data: {
     article_content: '<p>自我介绍1</p><p><img src="https://mirror-gold-cdn.xitu.io/168e088859e325b9d85?imageView2/1/w/100/h/100/q/85/format/webp/interlace/1" width="100" height="100"/></p><p>自我介绍2</p><p><img src="https://mirror-gold-cdn.xitu.io/168e088859e325b9d85?imageView2/1/w/100/h/100/q/85/format/webp/interlace/1" width="100" height="100"/></p><p>自我介绍3</p><p><img src="https://mirror-gold-cdn.xitu.io/168e088859e325b9d85?imageView2/1/w/100/h/100/q/85/format/webp/interlace/1" width="100" height="100"/></p>',
   }
});

小程序中运用高德地图绘制静态图

功能背景

在小程序的页面中,需要显示某个位置的具体地理坐标并做好标记;如果直接使用map组件,无法满足功能需求,同时会存在页面层级重叠的问题;所有就选择了高德地图微信小程序sdk,绘制静态图来呈现。

效果如图:

开发步骤

1.获取高德Key

点我获取Key>>
点我查看申请高德Key的方法>>

2.绘制静态图

简介:
由于微信内无法运行第三方地图,高德对广大开发者提供了静态地图功能,可快速生成一张地图图片,可以指定显示的地图区域、图片大小、以及在地图上添加覆盖物,如标签、标注、折线、多边形。 可用于快速生成一张个性化涂鸦的静态地图用于查看和分享。

静态图上绘制点

1、在页面的 js 文件中,实例化 AMapWX 对象,请求显示静态地图。

首先,引入 amap-wx.js 文件(amap-wx.js 从相关下载页面下载的 zip 文件解压后得到)。

xinxi.js:

var amapFile = require('path/to/amap-wx.js');//如:..­/..­/libs/amap-wx.js

然后,构造 AMapWX 对象,并调用 getStaticmap 方法。
其中,注意: 把百度地图坐标转换成高德,腾讯地图坐标

var zuobiaoArr = network.bMapTransQQMap(lng,lat)
Page({
  data: {
    pointObj:{
      lng:'您的坐标经度值',
      lat:'您的坐标纬度值'
    },
    src: ''
  },
  onLoad: function() {
    var that = this;
    var myAmapFun = new amapFile.AMapWX({key:"您的Key"});
    wx.getSystemInfo({
      success: function(data){
        var height = data.windowHeight;
        var width = data.windowWidth;
        var size = width + "*" + height;
        myAmapFun.getStaticmap({
          zoom: 8,
          size: size,
          scale: 2,
          markers: "mid,0xFF0000,A:"+pointObj.lng+","+pointObj.lat",
          success: function(data){
            that.setData({
              src: data.url
            })
          },
          fail: function(info){
            wx.showModal({title:info.errMsg})
          }
        })
      }
    })
  }
})

注意:
data.windowHeight,data.windowWidth获取的是整个窗口的高度和宽度,这里可以根据需求自己设定地图要显示的宽高。
markers: "mid,0xFF0000,A:"+pointObj.lng+";"+pointObj.lat",用于设置地图上要显示的标记坐标;如果要显示多个标记,格式为:

markers: "mid,0xFF0000,A:116.37359,39.92437;116.47359,39.92437"; // 多个坐标点以";"分割;

2、编写页面的 wxml 文件,搭建页面结构。

xinxi.wxml:

<view class="img_box">
  <img src="{{src}}">
</view>

3、编写页面的 wxss 文件,设置页面样式。

xinxi.wxss:

.img_box{
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
.img_box image{
  width: 100%;
  height: 100%;
}
……

4.注意细节:

如果你提供的 pointObj:{lng:'您的坐标经度值',lat:'您的坐标纬度值'}数据对象为百度地图的坐标值,我们需要将其转换为高德地图坐标值(它们的坐标计算方式不同);

转换方法如下:

//百度地图坐标转为高德,腾讯地图坐标
function bMapTransQQMap(lng, lat) {
    let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    let x = lng - 0.0065;
    let y = lat - 0.006;
    let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    let lngs = z * Math.cos(theta);
    let lats = z * Math.sin(theta);
    return {
        lng: lngs,
        lat: lats
    }
}
let pointObj = bMapTransQQMap(lng,lat); // 转换之后的坐标值;

结束:

如果你也一样喜欢前端开发,欢迎加入我们的讨论/学习群,群内可以提问答疑,分享学习资料;

欢迎添加群主微信和qq群答疑:

Guess you like

Origin www.cnblogs.com/wdlhao/p/11319487.html