Skip to content

H5常见错误解析

小程序组件初始化模板

js
// js
let app = getApp();
Component({
  /**
   * 组件的属性列表
   * 没有参数传入也不要把properties删掉
   */
  properties: {
    domain_url_front2: {
      type: String,
      value: '',
    },
    domain_url_plugins: {
      type: String,
      value: '',
    },
  },
  /**
   * 组件的初始数据
   */
  data: {},

  /**
   * 生命周期
   */
  ready() {},
  /**
   * 组件的方法列表
   */
  methods: {}
})
json
// json
{
  "component": true,//组件必有标识,遗漏编译会报错
  "usingComponents": {}
}

组件中,properties与data的属性不能同名,并且properties属性不能在组件内部修改

js
// js
properties:{
  title:{
    type: String,
    value: '',
  }
},
data:{
  title:'',//错误,禁止同名
},
js
// js
properties:{
  title_a:{
    type: String,
    value: '',
  }
},
data:{
  title_b:'',
},
onLoad(){
  this.setData({
    title_a:'重命名',//错误,禁止修改
    title_b:this.data.title_a + '标题',
  })
}

this.setData的使用

js
//H5不兼容
this.setData({ user }, () => {this.getOrderDetail();});
js
//需修改为
this.setData({ user });
this.getOrderDetail();

变量需提前声明并初始化,类型也要准确。赋值时不要改变数据类型。

js
//H5偶尔会报错
data: {},
onLoad(){
  this.setData({
    pics:[1,2,3,4],
  })
},
js
//需修改为
data: {
  pics:'',
},
onLoad(){
  this.setData({
    pics:'1.png,2.png,3.png,4.png',
  })
},

include的条件判断不生效

html
<!-- H5编译后条件判断会丢失 -->
<include wx:if="{{show}}" src="./style/style4.wxml" />
html
<!-- 修改为 -->
<view wx:if="{{show}}">
	<include  src="./style/style4.wxml" />
</view>

绑定事件一定在methods中定义,没用的事件记得删除

错误范例

html
<!-- 只绑定,methods中未定义 -->
<view bindtap="onTapOne"></view>
<!-- 绑定了多个 -->
<view bindtap="onTapOne" bindtap="onTapTwo" ></view>

正确方式

html
<!-- wxml -->
<view bindtap="onTapOne"></view>
js
// js
onTapOne(e){}

跨页面返回数据,比如在订单页跳转到选择地址,要把地址信息带回来。需配置json,例:

js
// 订单页json
{
  "keepAlive": true,
}
js
// 地址页json
{
  "changePrevious": true, 
}
js
// 地址页js
// 利用封装好的函数
this.setPrevData({
  info,
})
this.doPrevMethod('getDeliveryInfos');

转发常用写法

js
const app = getApp();
Page({
  onShareAppMessage() {
    let obj = {
      title: '申请入会',
      path: `/ziyuanhui/pages/shenqingruhui/shenqingruhui`,
      imageUrl: '',
    };
    return app.onShareAppMessage(obj);
  },

  onShareTimeline() {
    let obj = {
      same_share: true,
      title: '申请入会',
      query: ``,
      imageUrl: '',
    };
    return app.onShareTimeline(obj);
  },
});

单行省略号和多行省略号,width一定要给

css
/* 单行省略号 */
.danhang {
  width: 200rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
/* 多行省略号 */
.duohang {
  width: 200rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

有些组件和api无法兼容H5,只能写多套

js
// js
// 仅H5生效
if(app.app_type=='wechat'){}
html
<!-- wxml -->
<!-- 仅H5生效 -->
<view wx:if="{{app_type == 'wechat'}}"></view>