# 跨端小程序

## 微信小程序

整个小程序框架系统分为两部分：[**逻辑层**](https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/)（App Service）和 [**视图层**](https://developers.weixin.qq.com/miniprogram/dev/framework/view/)（View）。小程序提供了自己的视图层描述语言 `WXML`和 `WXSS`，以及基于 `JavaScript`的逻辑层框架，并在视图层与逻辑层间提供了数据传输和事件系统，让开发者能够专注于数据与逻辑。

原生微信小程序的语法和vue非常相似：

```jsx
Page({
  data: { },
  onLoad: function (options) { },
  onReady: function () {},
  onShow: function () { },
  onHide: function () {},
  onUnload: function () {},
  onPullDownRefresh: function () { },
  onReachBottom: function () { },
  onShareAppMessage: function () { }
})
```

```jsx
<view>
	<view>123</view>
	<button bindtap="{{a}}">click</button>
</view>
```

```css
.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
}
.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
}
.text-area {
		display: flex;
		justify-content: center;
}
.title {
		font-size: 36rpx;
		color: #8f8f94;
}
```

## 跨端小程序

uniapp是一款基于vue的跨端小程序开发框架，支持微信小程序、QQ小程序、支付宝小程序和APP。

`uni-app`简单来说是 **vue + 小程序api + 小程序组件 + 条件编译(跨端)**。

### 页面管理

微信小程序页面需要在`app.json`中注册，并且可以设置一些样式。

```jsx
{
	"pages": [{
		"path": "pages/component/index",
		"style": {
			"navigationBarTitleText": "组件"
		}
	}, {
		"path": "pages/API/index",
		"style": {
			"navigationBarTitleText": "接口"
		}
	}, {
		"path": "pages/component/view/index",
		"style": {
			"navigationBarTitleText": "view"
		}
	}],
	"condition": { //模式配置，仅开发期间生效
		"current": 0, //当前激活的模式（list 的索引项）
		"list": [{
			"name": "test", //模式名称
			"path": "pages/component/view/index" //启动页面，必选
		}]
	},
	"globalStyle": {
		"navigationBarTextStyle": "black",
		"navigationBarTitleText": "演示",
		"navigationBarBackgroundColor": "#F8F8F8",
		"backgroundColor": "#F8F8F8",
		"usingComponents":{
			"collapse-tree-item":"/components/collapse-tree-item"
		},
		"renderingMode": "seperated", // 仅微信小程序，webrtc 无法正常时尝试强制关闭同层渲染
		"pageOrientation": "portrait", //横屏配置，全局屏幕旋转设置(仅 APP/微信/QQ小程序)，支持 auto / portrait / landscape
		"rpxCalcMaxDeviceWidth": 960,
		"rpxCalcBaseDeviceWidth": 375,
		"rpxCalcIncludeWidth": 750
	},
	"tabBar": {
		"color": "#7A7E83",
		"selectedColor": "#3cc51f",
		"borderStyle": "black",
		"backgroundColor": "#ffffff",
		"height": "50px",
		"fontSize": "10px",
		"iconWidth": "24px",
		"spacing": "3px",
    "iconfontSrc":"static/iconfont.ttf", // app tabbar 字体.ttf文件路径 app 3.4.4+
		"list": [{
			"pagePath": "pages/component/index",
			"iconPath": "static/image/icon_component.png",
			"selectedIconPath": "static/image/icon_component_HL.png",
			"text": "组件",
      "iconfont": { // 优先级高于 iconPath，该属性依赖 tabbar 根节点的 iconfontSrc
        "text": "\ue102",
        "selectedText": "\ue103",
        "fontSize": "17px",
        "color": "#000000",
        "selectedColor": "#0000ff"
      }
		}, {
			"pagePath": "pages/API/index",
			"iconPath": "static/image/icon_API.png",
			"selectedIconPath": "static/image/icon_API_HL.png",
			"text": "接口"
		}],
		"midButton": {
			"width": "80px",
			"height": "50px",
			"text": "文字",
			"iconPath": "static/image/midButton_iconPath.png",
			"iconWidth": "24px",
			"backgroundImage": "static/image/midButton_backgroundImage.png"
		}
	},
}
```

[pages.json](https://uniapp.dcloud.io/collocation/pages.html)

微信小程序自身维护了一个页面栈，并提供一些API来供开发者调用页面栈。

对于路由的触发方式以及页面生命周期函数如下：

Untitled Database

### 生命周期

#### 页面生命周期

#### 小程序生命周期

挂起阶段需要注意

* 大部分小程序API在挂起阶段会失效
* websocket连接在挂起阶段会被强制中断
* …

**避免挂起**

* onShow/onHide
* 一些特定的小程序API

应用级生命周期

### 微信小程序开发者工具

* 模拟器
* 编辑器
* 调试器
  * 元素
  * 控制台
  * 源码
  * 网络
  * 性能
  * 内存（内存泄漏）
  * AppData （页面的变量）
  * Storage（类似浏览器的Storage）
  * Mock
  * 体验评分（类似LightHouse）
* 编译模式
* 预览
* 真机调试
* 项目设置

### 实现多端

uniapp实现多端的方法： **封装API + 条件编译**。

uni-app 已将常用的组件、JS API 封装到框架中，开发者按照 uni-app 规范开发即可保证多平台兼容，大部分业务均可直接满足。

但每个平台有自己的一些特性，因此会存在一些无法跨平台的情况。

条件编译是用特殊的注释作为标记，在编译时根据这些特殊的注释，将注释里面的代码编译到不同平台。

* \*写法：\*\*以 #ifdef 或 #ifndef 加 **%PLATFORM%** 开头，以 #endif 结尾。
* \#ifdef：if defined 仅在某平台存在
* \#ifndef：if not defined 除了某平台均存在
* **%PLATFORM%**：平台名称

Untitled Database

**%PLATFORM%** **可取值如下：**

Untitled Database

**支持的文件**

* .vue
* .js
* .css
* pages.json
* 各预编译语言文件，如：.scss、.less、.stylus、.ts、.pug

### 页面通讯

**监听器**

* **uni.$emit(eventName,OBJECT)**
* **uni.$on(eventName,callback)**
* **uni.$once(eventName,callback)**
* **uni.$off(\[eventName, callback])**

**URL queryString**

```tsx
details(id) {
    uni.navigateTo({
        url: "details?id="+id,
    });
},

onLoad(option) {
    console.log(option.id)
},
```

[uni-app官网 (dcloud.io)](https://uniapp.dcloud.io/api/window/communication.html)

### 内置组件

[uni-app官网 (dcloud.io)](https://uniapp.dcloud.io/component/view.html)

[视图容器 | 微信开放文档 (qq.com)](https://developers.weixin.qq.com/miniprogram/dev/component/)

### API

[基础 | 微信开放文档 (qq.com)](https://developers.weixin.qq.com/miniprogram/dev/api/)

[uni-app官网 (dcloud.io)](https://uniapp.dcloud.io/api/)

### 注意

* uniapp 异步API通常的回调风格，但是只要你不传入 success、fail、complete 等 callback 参数，那么API返回值就会转换成Promise。

```tsx
 // 正常使用
 const task = uni.connectSocket(
  success(res){
   console.log(res)
  }
 )

 // Promise 化
 uni.connectSocket().then(res => {
   // 此处即为正常使用时 success 回调的 res
   // uni.connectSocket() 正常使用时是会返回 task 对象的，如果想获取 task ，则不要使用 Promise 化
   console.log(res)
 })
```

* uni.$on是全局级别的，跨页面跨组件，尽量减少使用，并且页面销毁时(onUnload)记得销毁事件监听器(uni.$off)
* uni.request() Post请求默认的编码格式是`application/json`，可以通过改变请求头`'content-type’` 字段来改变。

```tsx
uni.request({
    url: 'https://www.example.com/request', //仅为示例，并非真实接口地址。
    data: {
        text: 'uni.request'
    },
    header: {
        'custom-header': 'hello' //自定义请求头信息
    },
    success: (res) => {
        console.log(res.data);
        this.text = 'request success';
    }
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://1425816423.gitbook.io/my-knowledge-base/jing-yan-ji-lu/jing-yan-zong-jie/kua-duan-xiao-cheng-xu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
