4.微信小程序之自定义组件

来理一理自定义组件的思路
距离下班还有一小时
╮(╯▽╰)╭

1.组件简单使用

组件
组件

注意:com.json中

{
  "component": true,  //自定义组件声明
  "usingComponents": {}  //可选项,用于引入其他组件
}

com.wxml

<view class="container">
  <view class='red' bindtap='onRed'></view>
  <view class='gray'></view>
</view>

com.wxss

.container{
  height: 400rpx;
  width: 400rpx;
  border: 1rpx solid #000;
  color: #fff;
}

.red{
  width: 400rpx;
  height: 200rpx;
  background: red;
}
.gray{
  width: 400rpx;
  height: 200rpx;
  background: gray;
}

组件写好了,接下来引用。
要使用组件的页面
在这里插入图片描述
打开要引入组件的页面,test.json

{
  "usingComponents": {
    "apple":"/pages/com/com"
  }
}

test.wxml

<apple></apple>

引入成功。什么?组件写得太简单了,不要在意这种细节。。。
在这里插入图片描述

2.给组件绑定事件

com.wxml

<view class='red' bindtap='onRed'></view

com.js

methods: {
    onRed() {
      console.log('打印啦啦啦,红色');
    }
  }

当点击红色块时,可以看见控制台打印输出。

3.页面向组件传值

test.wml

<apple now-in="index" bind:getRed="onGet"></apple>

组件com.js

properties: {
    nowIn:String
  },

com.wxml

<view class="container">
  <view class='red'></view>
  <view class='gray'></view>
</view>
<view>{{nowIn}} is here</view>

结果
在这里插入图片描述

这里我们要注意,在页面定义自定义属性时是 “now-in”,在组件js中接收是 “nowIn”,驼峰的写法。
可以使用this.data,可看见传过来的数据。

4.组件向页面传值

com.js

methods: {
    onRed() {
      console.log('打印啦啦啦,红色');
      this.triggerEvent("getRed", this.data.nowIn);
      console.log(this.data);
    }
  }

test.wxml

<apple now-in="index" bind:getRed="onGet"></apple>

texst.js

onGet(e){
    console.log(e);
    this.setData({
      hhh:e.detail
    })
  }

在这里插入图片描述

在detail中,就可以看见我们想要传的值,nowIn=“index”, 完成传值。
啦啦啦距离下班还有27分钟,嘿嘿嘿~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值