小程序-组件开发

新建组件

新建component文件夹,在建个test文件夹,然后新建Component
在这里插入图片描述
与普通页面不同的是,这里的js中是Component({ }),从父组件接受的参数放在properties:{}中,
函数写在methods:{}中;
在这里插入图片描述

其他页面使用组件

1、在xxx.json文件中注册:

{
	"usingComponents": {
	"test":"/component/test/index"
	}
}

2、xxx.wxml中,使用组件

<test></test>

3、使用slot插槽

  • 使用一个插槽时直接使用,不用在组件的js文件中设置,但是使用多个插槽时,需要配置mutipleSlots: true
Component({
	properties:{},
	options:{
		mutipleSlots: true,
	},
	data:{},
	methods:{}
})
  • 组件的wxml文件:
<view>
	小程序<slot name="slot1"></slot>组件
	<slot name="slot2"></slot>
	<slot name="slot3"></slot>
</view>
  • 页面中使用:
<test>
	<text slot="slot1">小程序</text>
	<text slot="slot2">slot</text>
	<text slot="slot3">组件</text>
</test>

参数传递

从父页面传递到子组件

  • 页面中使用 prop-name="",传递参数
<test prop-name="桃子">
	<text slot="slot1">小程序</text>
	<text slot="slot2">slot</text>
	<text slot="slot3">组件</text>
</test>
  • 子组件使用properties接受:
Component({
	properties:{
		propName:{
			type: String
		}
	},
	options:{
		mutipleSlots: true,
	},
	data:{},
	methods:{}
})
  • 子组件模板中使用:
<view>
	小程序<slot name="slot1"></slot>组件
	<slot name="slot2"></slot>
	<slot name="slot3"></slot>
	<text>{{propName}}</text>
</view>

子组件向父页面传参

<view>
	小程序<slot name="slot1"></slot>组件
	<slot name="slot2"></slot>
	<slot name="slot3"></slot>
	<text>{{propName}}</text>
	<button catchtap="bindGoods">提交</button>
</view>
  • 在子组件中触发bindGoods事件:
Component({
	properties:{
		propName:{
			type: String
		}
	},
	options:{
		mutipleSlots: true,
	},
	data:{},
	methods:{
		bindGoods(){
			const goods = {
				name: '香蕉',
				color: 'yellow'
			}
			this.triggerEvent('bindGoods', goods);
		}
	}
})
  • 父组件监听bindGoods事件
<test prop-name="{{name}}" bind:bindGoods="getGoods">
	<text slot="slot1">小程序</text>
	<text slot="slot2">slot</text>
	<text slot="slot3">组件</text>
</test>

js文件

Page({
	data:{
		name:'桃子',
	},
	getGoods(e){
		console.log(e);
	}
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值