关于组件得官方文档描述,请参考自定义组件,本篇仅简述一下开发中得注意点。
我的组件包目录是和pages同级的,这个看个人。
1.组件的声明
需要在share.json里将component设置为true
{
"component": true,
"usingComponents": {}
}
2.组件的引用
假如想在index里引用share组件,则需要在index.json里配置usingComponents,例:
{
"usingComponents": {
"component-share": "/component/share/share"
},
然后在页面内引用该组件:
<component-share bindintoout="changesharemsg" share-msg="{{shareMsg}}"></component-share>
3.贴一下share的代码
// component/share/share.js
var util=require('../../utils/util.js')
Component({
/**
* 组件的对外属性,是属性名到属性设置的映射表
* 组件内部 遵循驼峰规则 引用页面外部使用"-"连接
*/
properties: {
shareMsg:String
},
lifetimes: {
attached: function () {
// 在组件实例进入页面节点树时执行
console.log('在组件实例进入页面节点树时执行')
},
detached: function () {
// 在组件实例被从页面节点树移除时执行
},
},
observers: {
'shareMsg': function (newVal) {
console.log('节点数据发生变化时执行:' + newVal)
}
},
pageLifetimes: {
show: function () {
// 引用页面被展示
console.log('引用页面被展示')
},
hide: function () {
// 引用页面被隐藏
console.log('引用页面被隐藏')
},
resize: function (size) {
// 引用页面尺寸变化
console.log('引用页面尺寸变化')
}
},
/**
* 组件的内部数据,和 properties 一同用于组件的模板渲染
*/
data: {
innerData:"内部数据,外部不可更改"
},
/**
* 组件的方法列表
*/
methods: {
//更改外部数据
toOut:function(){
var that=this
var msg = util.formatTime(new Date())
var option={
"msg": msg
}
that.triggerEvent('intoout', option)
}
}
})
<!--component/share/share.wxml-->
<view>{{shareMsg}}</view>
<view>{{innerData}}</view>
<button bindtap="toOut">点击我更改外部数据</button>
4.贴一下index代码
//index.js
var util=require('../../utils/util.js')
//获取应用实例
const app = getApp()
Page({
data: {
shareMsg:"外部数据,通过properties内定义的属性传递"
},
onLoad: function () {
var that=this
that.setData({
shareMsg: util.formatTime(new Date())
})
},
changesharemsg: function (e, option){
console.log(e)
var that = this
that.setData({
shareMsg: e.detail.msg
})
}
})
<!--index.wxml-->
<!-- 组件内部 遵循驼峰规则 引用页面外部使用"-"连接 -->
<component-share bindintoout="changesharemsg" share-msg="{{shareMsg}}"></component-share>
相关的参数的描述,代码中已注释。
5.说明一下,demo做了什么
5.1 首先,组建内shareMsg是没有初始值的。
在index页面onLoad内,给shareMsg赋予了一个初始值,通过
share-msg="{{shareMsg}}
传递给组件内的shareMsg属性
5.2 点击button按钮,触发组件内的toOut事件,通过triggerEvent传递给绑定的index页面的事件changesharemsg,option为传递的参数
that.triggerEvent('intoout', option)
更改了index里的shareMsg值,然后又传递给了组件,重新渲染页面。
6.仅供参考
项目地址:wechat-component