原生微信小程序开发记录

1. 拿到项目 先构建

2.小程序与普通网页开发的区别

网页开发渲染线程和脚本线程是互斥的,这也是为什么长时间的脚本运行可能会导致页面失去响应,而在小程序中,二者是分开的,分别运行在不同的线程中。网页开发者可以使用到各种浏览器暴露出来的 DOM API,进行 DOM 选中和操作。而如上文所述,小程序的逻辑层和渲染层是分开的,逻辑层运行在 JSCore 中,并没有一个完整浏览器对象,因而缺少相关的DOM API和BOM API。

3.按需加载

"lazyCodeLoading": "requiredComponents"

4.配置scss

在project.config.json 文件 setting 加: 

  "setting": {
    "useCompilerPlugins": [
      "sass"
    ],
}

5.父子组件之间传值
事件传递

父组件:

<!-- parent-component.wxml -->
<child-component bind:childEvent="onChildEvent"></child-component>


// parent-component.js
Page({
  onChildEvent: function(event) {
    console.log('接收到子组件传递的值:', event.detail);
    // 处理从子组件传递过来的值
  }
})

子组件:

<!-- child-component.wxml -->
<button bindtap="onButtonClick">点击传递值</button>


// child-component.js
Component({
  methods: {
    onButtonClick: function() {
      var value = '需要传递的值';
      this.triggerEvent('childEvent', value); // 触发自定义事件,并传递值
    }
  }
})

数据绑定

父组件:

<!-- parent-component.wxml -->
<child-component value="{{value}}"></child-component>

// parent-component.js
Page({
  data: {
    value: '需要传递的值'
  }
})

子组件:

<!-- child-component.wxml -->
<view>{{value}}</view>


// child-component.js
Component({
  properties: {
    value: {
      type: String,
      value: '' // 设置默认值
    }
  }
})

6.配置文件引入路径:

全局配置文件app.json:

{
  "resolveAlias": {
    "@/*": "/*"
    "~/*": "/*",
    "~/origin/*": "origin/*",
    "@utils/*": "utils/*",
    "subBUtils/*": "subpackageB/utils/*"
  }
}
7.(开发版、体验版、正式版)获取对应的环境配置信息

写个配置config.env.js 代码如下:

const envConf = {
  develop: {
    apiUrl: 'http://localhost:3000/api'
  },
  trial: {
    apiUrl: 'https://trial.example.com/api'
  },
  release: {
    apiUrl: 'https://api.example.com/api'
  }
}

module.exports = {
    env: envConf[__wxConfig.envVersion]
}

其他地方使用

import { env } from './config/config.env.js';

env.apiUrl  就可以了得到链接地址了

8.wx.getSetting() 是微信小程序提供的一个 API 方法,用于获取用户的当前设置信息。通过调用该方法,小程序可以获取到用户对小程序的授权信息,例如用户是否授权了小程序获取用户信息、地理位置、通讯录等权限。

wx.getSetting({
  success(res) {
    if (res.authSetting['scope.userInfo']) {
      // 用户已授权获取用户信息
      wx.getUserInfo({
        success(userInfoRes) {
          console.log(userInfoRes.userInfo);
          // 获取用户信息成功,可以在这里处理用户信息
        }
      });
    } else {
      // 用户未授权获取用户信息,可以引导用户打开授权设置页进行授权
    }
  }
});

9.微信小程序input 聚焦谈起软键盘,样式上移动解决方案。

1.把整个页面 高度100%。

2.聚焦的时候高度改为 100vh,overflow:hidden;

3.失去焦点的时候,高度变回原来的100%。

具体案例:

wxss代码:

.home-contain {
    height: 100vh;
    overflow: hidden;
}
.home-contain-no {
    height: 100%;
    overflow: auto;
}

wxml代码:

//最外层 
<view class="{{show?'home-contain':'home-contain-no'}}">
   <input  placeholder="请输入" bindfocus="handlefocus" bindblur="handleblur"/>
 </view>

js代码:

    handlefocus(){
        this.setData({show:true})
    },
    handleblur(){
        this.setData({show:false})
    },

10.微信支付

const wxPayment = (param) => {
    return new Promise((resolve, reject) => {
        wx.requestPayment({
            timeStamp: param.timeStamp,
            nonceStr: param.nonceStr,
            package: param.package,
            signType: param.signType,
            paySign: param.paySign,
            success(res){
                console.log('requestPayment res ==>', res);
                resolve(res);
            },
            fail(err){
                resolve(err);
                // wx.showToast({
                //     title: '支付失败',
                //     icon: 'none'
                // })
            }
        })
    })
}



      // 调用微信支付方法

   async confirmPay(){
      const payRes = await wxPayment(param);
      if(payRes.errMsg == 'requestPayment:ok'){
          wx.showToast({
              title: '支付成功',
              icon: 'none'
          })
          setTimeout(() => {
              wx.redirectTo({
                  url: '/pages/**',
              })
          }, 800)
      }else{
      //未支付
      }
  }

11.微信登录方式

静默登录示例

// 小程序端代码
wx.login({
  success: function (res) {
    if (res.code) {
      // 将 code 发送到后台服务器
      wx.request({
        url: 'https://example.com/login',
        method: 'POST',
        data: {
          code: res.code
        },
        success: function (response) {
          // 处理服务器返回的数据,通常会得到用户的唯一标识 openid 和会话密钥 session_key
          const { openid, session_key } = response.data;
          // 将 openid 和 session_key 存储到本地,用于后续的用户验证
          wx.setStorageSync('openid', openid);
          wx.setStorageSync('session_key', session_key);
        }
      });
    } else {
      console.error('登录失败!' + res.errMsg);
    }
  }
});

显示式登录示例: 

// 小程序端代码
wx.getUserInfo({
  success: function (res) {
    const userInfo = res.userInfo;
    const nickName = userInfo.nickName;
    const avatarUrl = userInfo.avatarUrl;
    // 将用户信息发送到后台服务器进行处理,完成用户的登录或授权操作
  },
  fail: function (res) {
    console.error('获取用户信息失败!' + res.errMsg);
  }
});
12.微信小程序分享
 
// 在需要分享的页面中
Page({
  // 页面数据
  data: {
    // 页面数据
  },
  // 页面加载时触发
  onLoad: function (options) {

    //"shareAppMessage"表示“发送给朋友”按钮,"shareTimeline"表示“分享到朋友圈”按钮
    // 显示转发按钮
    wx.showShareMenu({
      withShareTicket: true, // 是否使用带 shareTicket 的转发
      menus: ['shareAppMessage', 'shareTimeline']
    });


  },
  // 监听用户点击转发按钮的事件
  onShareAppMessage: function () {
    // 返回需要分享的内容
    return {
      title: '分享标题', // 分享标题
      path: '/pages/index', // 分享页面的路径
      imageUrl: '/images/share.jpg' // 分享图片的地址
    };
  },
  // 其他页面逻辑
});
13.微信小程序拨打电话
wx.makePhoneCall({
  phoneNumber: '电话号码',
  success: function(res) {
    console.log('拨打电话成功:', res);
  },
  fail: function(err) {
    console.error('拨打电话失败:', err);
  }
});
14.微信剪贴板
wx.setClipboardData({
  data: '要复制的文本内容',
  success: function(res) {
    console.log('复制成功:', res);
    // 显示成功提示
    wx.showToast({
      title: '复制成功',
      icon: 'success'
    });
  },
  fail: function(err) {
    console.error('复制失败:', err);
    // 显示失败提示
    wx.showToast({
      title: '复制失败,请重试',
      icon: 'none'
    });
  }
});
15. 微信小程序分包

注意事项:

  • tabBar 页面必须在主包内
  • subpackage 的根目录不能是另外一个 subpackage 内的子目录
  • 整个小程序所有分包大小不超过 20M
  • 单个分包/主包大小不能超过 2M
16.微信小程序音频
const innerAudioContext = wx.createInnerAudioContext({
  useWebAudioImplement: false // 是否使用 WebAudio 作为底层音频驱动,默认关闭。对于短音频、播放频繁的音频建议开启此选项,开启后将获得更优的性能表现。由于开启此选项后也会带来一定的内存增长,因此对于长音频建议关闭此选项
})
innerAudioContext.src = '**.mp3'

innerAudioContext.play() // 播放

innerAudioContext.pause() // 暂停

innerAudioContext.stop() // 停止

innerAudioContext.destroy() // 释放音频资源

17.地址选择器
   wx.chooseAddress({
            success(res) {

            },
            fail(err) {
                console.error('err ==>', err);
            }
    })
18.判断是否本地文件存在
    //判断 是否本地有
    handlePdfHas(path) {
      const fs = wx.getFileSystemManager();
      const filePath = path; //文件路径
      try {
        const data = fs.readFileSync(filePath, "binary");
        // 文件存在,可以处理数据
        return true;
      } catch (e) {
        return false;
        // 文件不存在或读取失败
      }
    },
19.事件管理

创建eventManager.js
 

// eventManager.js  
class EventManager {
  constructor() {
    this.eventListeners = {};
  }

  // 监听事件  
  on(eventName, callback) {
    if (!this.eventListeners[eventName]) {
      this.eventListeners[eventName] = [];
    }
    this.eventListeners[eventName].push(callback);
  }

  // 触发事件  
  emit(eventName, data) {
    const callbacks = this.eventListeners[eventName];
    if (callbacks) {
      callbacks.forEach(callback => {
        callback(data);
      });
    }
  }

  // 移除事件监听器  
  off(eventName, callback) {
    const callbacks = this.eventListeners[eventName];
    if (callbacks) {
      this.eventListeners[eventName] = callbacks.filter(cb => cb !== callback);
    }
  }
}

// 创建全局事件管理器实例  
const eventManager = new EventManager();

// 将实例暴露给全局  
export default eventManager;

监听事件


import eventManager from '@/utils/eventManager';
    
eventManager.on('cartNumber', (number) => {

  _this.handleNumberTab(number)
});

发布事件

       // 发布事件  
        eventManager.emit('cartNumber', cart.length);

移除事件
 

    // 页面卸载时移除事件监听器,避免内存泄漏  
    eventManager.off('cartNumber');
20.自定义tabbar 

可以用this.getTabBar().init();初始化

21.微信小程序获取二维码信息
 const query = wx.getLaunchOptionsSync().query; // 或使用onAppShow中获取的query  
 const scene = query.scene; // 假设scene是通过URL参数传递的(实际情况可能不同)  
22.分享图片:show-menu-by-longpress
 <image wx:if="{{imgUrl}}" src="{{imgUrl}}" mode="widthFix" show-menu-by-longpress />
23.设置标题
  wx.setNavigationBarTitle({
     title: '上传作品'
  });
24.没有找到可以构建的 NPM 包,请确认需要参与构建的 npm 都在 `miniprogramRoot` 目录内,或配置 project.config.json 的 packNpmManually 和 packNpmRelationList 进行构建 [1.06.2210310][win32-x64]

project.config.json的settings选项下:

    "packNpmManually": true,
    "packNpmRelationList": [
      {
        "packageJsonPath": "./package.json",
        "miniprogramNpmDistDir": "./miniprogram/"
      }
    ],
    "es6": true,
    "enhance": true

25.阻止滑动
<!-- 遮罩层 wxml 结构 -->
<view class="mask" catchtouchmove="stopPropagation"></view>


 stopPropagation: function(e) {
    // 阻止事件冒泡
    e.stopPropagation();
  }

26.微信地图中心点位置,定位不对。我采取的是连续设置了第二次在setTimeout一下,定位就对上位置了
      this.setData({
        scale: 14,
        latitude: item[0].latitude,
        longitude: item[0].longitude,
      
      })

      setTimeout(() => {
        this.setData({
          scale: 14,
          latitude: String(item[0].latitude),
          longitude: String(item[0].longitude),
        })
      }, 100);
27.微信地图导航
		handleRouter(){
		let	MapContext = wx.createMapContext('myMap')//myMap 是地图 id
			MapContext.openMapApp({
				longitude: Number(this.data.infoItem.longitude),
				latitude:Number(this.data.infoItem.latitude),
				destination:this.data.infoItem.nature_village,
				success:function(e){
					console.log(e,999999);
				},
				fail:function (e){
					console.log(e,88888);
				}
			})
		},
28.获取键盘高度变化
    wx.onKeyboardHeightChange(res => {
      console.log(res.height, 8888)
    })
29.阻止冒泡

父级用 bindtap  子级别用catchtap

30.获取定位

  //获取定位信息
  handlePosition() {
    // 获取用户当前的地理位置信息
    wx.getLocation({
      // type: 'wgs84', // 返回可以用于wx.openLocation的经纬度
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        const speed = res.speed
        const accuracy = res.accuracy
        // 可以使用这些数据进行后续操作
        console.log(latitude, longitude, speed, accuracy)
      },
      fail(err) {
        // 处理失败情况
        console.error("获取位置失败", err)
      }
    })
  },

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值