1.组件的使用
- 新建component
- 引用
xxx.json { "component": true, "usingComponents": { "item":url} } <item></item>
2.插槽
- 默认插槽
<item> <text>嵌套内容</text> </item>
组件内部<slot></slot>
- 具名插槽
1)组件的js中option定义
options: { multipleSlots: true, //开启多个插槽 },
2)传入
<text slot="pre">¥</text>
3) 接收
<slot name="pre"></slot>
3.样式
- 各组件样式互不干扰
配置样式隔离
options: {
styleIsolation: "isolated",
//isolated隔离,apply-shared子可以用父,shared相互影响
},
-
外部类
组件1.定义 :
externalClasses:["item-class"]
2.传入的参数(只读)
properties: { "title": { type: String, value: '' wxml模板中使用 class="item item-class" } },
页面
1.wxml定义
<item title="外部类" item-class="myclass"> </item>
2.wxss 定义css
.myclass{ height: 200rpx !important; color:#f00 !important; }
4.参数
- 传递(参数只读)
<item title="标题">
- 获取
properties: {
"title": {
type: String,//数据类型
value: ''//默认值
},
}
- 使用
{{title}}
5.事件传递
- 子元素发送事件
this.triggerEvent("事件名称",{时间对象})
- 父元素监听
<item bind:时间名="处理函数">
- 处理函数
function 处理函数(e){ //e就是事件对象 }
6.Component
-
外部类
externalClasses:["item-class"],
-
传入的参数(只读)
properties: { "title": { type: String, value: '' wxml模板中使用 class="item item-class" } },
-
选项
options: { multipleSlots: true, //开启多个插槽 styleIsolation: "isolated", 样式隔离 },
-
数据:data
-
组件的方法:methods
-
生命周期:pageLifetimes
7.生命周期
-
lifetimes 生命周期
lifetimes:{ created(){ console.log("创建完毕,有this 不能setData") }, attached(){console.log("挂载,可以设置data"); }, ready(){console.log("组件挂载完毕"); }, move(){console.log("组件移动"); }, detached(){console.log("销毁"); }, error(){console.log("组件发生错误"); } },
-
pageLifetimes 页面生命周期
pageLifetimes:{ show(){console.log("页面显示") }, hide(){console.log("页面隐藏"); }, resize(){console.log("视图变化"); } },
7.第三方组件
1. npm使用
- 在项目中
npm init -y
创建packge.json - 详情,本地设置,使用npm模块
- 工具,构建npm
2.weapp使用
- 安装
npm i @vant/weapp -S--production
- 配置
{ "usingComponents": { "van-button":"@vant/weapp/button/index" }}
- 使用
<van-button type="default">默认按钮</van-button>
8. 分包
为什么需要分包?
- 小程序是动态加载(没有安装),主包源代码限制2M,通过分包可以上传16M的内容(大型小程序项目)分包是很有必要的
- 即使小程序主包只有2M,下载打开小程序是比较慢的,主包只有一个页面,切换其他页加载分包内容(优化主页加载速度)
- 只有用户进入到分包页面,才会加载分包页面(按需加载)
- 分包预加载
- 只有进入页面才开始加载(如果分包较大,进入页面等待时间较长)
- 当进入到某个特定的页面的时候,提前加载分包资源
"preloadRule": { "pages/user/user":{ "network": "all", "packages": ["sub"] } },
- 当进入到pages/user/user页面的时候,并且网络空闲,所有网络预加载分包sub
- 哪些做主包,哪些做分包
底部栏页面做主包,二级页面做分包