组件的作用
1、页面拆分成组件,其分离性、简洁易维护性远大于复用性。
2、组件在本项目中复用性很大,但想复用到其他项目时:不要去追求一行代码都不改的复用
组件包括
1、properties 组件的属性列表,外部可访问;对属性做处理 observer
2、data 组件的初始数据,外部不能访问
3、methods 组件的方法列表
目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型)
Component({
properties: {
book: Object,
liketwo:{
type: Boolean,
value: false //boolean值默认为false,所以这里的value是省略的
},
count:{
type:String,
observer:function(newVal,oldVal,changedPath){
let val =newVal<10?'0'+newVal:newVal
this.setData({
_count:val //这里是赋值给data数据中的_count,如果改为赋值给properties的count会导致无线递归修改
})
}
}
},
data: {
Src: 'images/like.png',
_count:'0'
},
methods: {
onLike:function(event){
}
}
})
调用组件
json文件中引入调用的组件
{
"usingComponents":{
"v-like":"/components/like/index",
"v-movie":"/components/classic/movie/index"
}
}
wxml中赋值属性
<v-like liketwo="{{}}" /> //v-like调用组件,liketwo赋值属性
behavior行为
behaviors 是用于组件间代码共享的特性
定义:export+import
调用:behaviors:[ ]
Behavior的定义和component是一样的 properties、data、methods;Behavior类似于构造器;
单个项目中behavior不明显,但多个项目复用或组件库时,就非常有用
behavior多继承,采取后覆盖前,但生命周期不覆盖,继承3个行为,就可调用3次行为同生命周期函数
组件css调用引入css
@import "../abc.wxss";
slot插槽
<!-- 组件模板 -->
<view class="wrapper">
<slot name="before"></slot>
<view>这里是组件的内部细节</view>
<slot name="after"></slot>
</view>
<!-- 组件JS -->
Component({
options: {
multipleSlots: true // 在组件定义时的选项中启用多slot支持
}
})
<!-- 引用组件的页面模板 -->
<view>
<component-tag-name>
<!-- 可由组件调用方规定style样式,让组件更多样化 -->
<view slot="before" class="diy">这里是插入到组件slot name="before"中的内容</view>
<view slot="after">这里是插入到组件slot name="after"中的内容</view>
</component-tag-name>
</view>
外部样式
<!-- abc组件模板 -->
<!-- 在小程序里外部样式是否能完全替换普通样式是不确定的,所有外部样式要加important-->
<view class="wrapper style-a">
<view>...</view>
</view>
<!-- 组件JS -->
Component({
externalclasses:['style-a']
})
<!-- 引用组件的页面模板 -->
<view>
<abc style-a="index-a">
</abc>
</view>
<!-- 引用组件的页面css -->
.index-a{color:red !important}
WXS
WXS(WeiXin Script)是小程序的一套脚本语言,结合 WXML,可以构建出页面的结构
wxs与JS很像,但并不是JS,ES6语法也均不支持如let、const,ES5支持不错。
像JS一样可以写在wxml中也可以独立wxs文件
写在wxml中
<wxs module="m1">
var msg = "hello world";
module.exports.message = msg;
</wxs>
<view> {{m1.message}} </view>
写在wxs中
//WXML文件
//类似ES6的import
<wxs src="../aaa.wxs" module="bbb" />
<text class="content">{{bbb.format(xxx)}}</text>
//aaa.WXS文件
//类似ES6的exports
module.exports = {
format:format,
limit:limit
}
如果是对js中数据更新,那么记得判断一下。