小程序学习--点击按钮实现分享(组件复用)
首先,第一步,创建一个按钮的组件,方便复用,当点击按钮时候,会跳出是否授权的对话框:
组件的wxml代码:
<button bind:getuserinfo="onGetUserInfo" open-type="{{openType}}" plain="{{true}}" class="container">
<slot name="img"></slot>
</button>
绑定事件onGetUserInfo 定义opentype属性 slot标签是一个组件插槽
组件的JS代码:
component({
/**
* 组件的属性列表
*/
//开启插槽
options:{
multipleSlots:true
},
properties: {
openType:{
type:String
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
onGetUserInfo(event){
this.triggerEvent('getuserinfo',event.detail,{})
}
}
})
在JS中,定义options开启组件的插槽:true
定义openType属性的数据类型为字符串,
在刚刚wxml代码的绑定的事件,编写触发器事件,获取用户信息,getuserinfo
组件编写完之后,在page页面中进行应用,
首先打开page页面的json文件:(进行配置 组件的调用)
page页面的json代码:
{
"usingComponents":{
"v-button":"/components/image-button/index"
}
}
上面的v-button就是我给刚刚的组件取得名字,可以拿到page页面的wxml中进行调用
page页面的wxml代码:调用按钮组件 open-type为share 分享 slot为组件开启的插槽
<!-- 分享按钮 -->
<v-button class="share-btn" open-type="share">
<image class="share" slot="img" src="/images/icon/share.png"/>
</v-button>
接下来看在PC端测试的效果: