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