您的位置:首页 > 移动开发 > 微信开发

关于小程序自定义组件

2019-02-22 16:54 218 查看

新建目录components。

在components中新建目录,即组件名如swiper_c。

在swiper_c中新建component,取名swiper_c,然后生成文件模板wxml、wxss、js、json。

在wxml和wxss中的写法与页面写法类似。

注意:

    需要在json文件中添加设置component:true将其设置为组件(新建组件时已设置)

    wxml中需绑定方法才能在调用组件时使用方法;

    如果需要在组件中添加slot(节点),需要在wxml中添加<slot></slot>

[code]<view bindtap='showPanel'>
<slot></slot>
……
</view>

    如果需要添加多个节点,在组件中需定义,每个slot用name来区分

[code]options: {
mutipleSlots: true    //启用多slot支持
}

    wxss中不要用标签选择器定义样式,否则会影响其它组件的样式。

在js中

[code]component({
properties: {
//属性列表
title: {
type: String,    //必填,设置类型
value: '标题'    //可选,设置初始值
},
……
},
data: {
flag: true
},
methods: {
showPanel: function(){
this.setData({
flag: !this.data.flag,
})
},
hidePanel: function(){
this.setData({
flag: !this.data.flag,
})
},
_inner() {     //内部私有方法建议以下划线开头
this.triggerEvent('inner_f');    //自定义组件触发时间需要用triggerEvent方法
}
}
})

tips: triggerEvent('',{ behavior },{})中,第一个参数是自定义事件名,在页面调用组件时bind的名称,第二个对象可以实现页面对组件属性的获取,用event.detail.behavior取得该数据,第三个是对事件的设置。

组件的调用

在调用组件的目录下的json添加 “useingComponent”:{ “swiper_c”:"{{swiper_c的相对路径}}" } 以使用组件。

wxml中使用组件,组件调用时给它一个id,以便在js中获得该组件,用以后续使用组件中的方法。

[code]<swiper_c id="swiper_c" title='新标题' …… bind:inner_f='_inner'>
//加入插入节点
<text>这是通过slot插入的内容</text>
</swiper_c>

js中调用

[code]onReady: function(){
this.swiper_c = this.selectComponent("#swiper_c");
},

_inner(){
this.swiper_c.hidePanel();
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: