一、创建组件
- 新建组件文件夹
习惯组件目录放在src下面,在src/components/privPopup,跟其他的页面目录一样,新建wxml/js/json/wxss四个文件
- 在wxml里面,跟普通的页面一样的写法
<view class="st-modal-btns">
<label role="button" class="st-modal-btn border-top-1px border-right-1px st-button st-button-default" bindtap="onCancel">
<span class="st-button__text">取消</span></label>
<label role="button" class="st-modal-btn border-top-1px st-button st-button-default st-modal-btn_highlight" bindtap="onConfirm"><span class="st-button__text">已阅读并同意</span></label>
</view>
- 在json文件里面进行自定义组件声明,将component字段声明为true。其他的wxml和wxss写法和其他页面类似。
{
"component": true
}
- 组件js文件里面使用Component({})来注册,并提供组件的属性定义、内部数据和自定义方法,组件的属性值和内部数据将用于wxml的渲染。其中属性值是可由组件外部传入的。
Component({
data: {
closed: false
},
properties: {
visible: {
type: Boolean
},
notConfirmList: {
type: Array,
},
},
methods: {
onCancel() {
this.triggerEvent('close');
},
onConfirm() {
this.triggerEvent('confirm');
},
clickProtocol(e) {
let goProtocol = {
val: e.currentTarget.dataset.url
};
this.triggerEvent('goProtocol', goProtocol);
}
}
});
二、引入组件
account/index.wxml
<privpopup visible="{{popupVisible}}" notConfirmList="{{notConfirmList}}" bind:close="onPopupClose" bind:confirm="onPopupConfirm" bind:goProtocol="goProtocol"/>
account/index.json进行引用声明,提供自定义组件的标签名和自定义组件的引用路径
{
"usingComponents": {
"privpopup": "../../components/privPopup/index",
}
}
三、父子组件传值通信
1. 子组件向父组件传递数据
- 子组件往父组件传值
例如:我要把弹窗里面的协议用户点中的url传到父组件中,然后发生跳转
clickProtocol(e) {
let goProtocolDetail = { // detail对象,提供给事件监听函数
val: e.currentTarget.dataset.url
};
this.triggerEvent('goProtocol', goProtocolDetail);
}
- 父组件获值
goProtocol(e) {
// 获取当前页面栈
let pages = getCurrentPages();
let fromPage = pages[pages.length -1].route;
let url = e.detail.val; // 通过detail对象获取到子组件传递过来的值val
let link = `/pages/webview/index?url=${encodeURIComponent(url)}&frompage=${fromPage}`;
wx.navigateTo({
url: link
})
}
2. 父组件向子组件传递数据
account/index.wxml
<privpopup visible="{{popupVisible}}" type="{{popupType}}" notConfirmList="{{notConfirmList}}"/>
- 父组件传值
data: {
popupVisible: false,
notConfirmList: [],
},
- 子组件获值
子组件以properities的方式接收值,属性会有指定数据类型type和值value
properties: {
visible: {
type: Boolean
},
type: {
type: Number,
value: 1
},
notConfirmList: {
type: Array,
},
},
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。