微信小程序学习笔记三(持续更新)---小程序组件通信

参照这里
这里将重要的点贴一下:

一、项目目录结构

在项目同级目录新建components文件夹,新建component会生成wxml,wxss,js,json文件。将所有的公共组件都写在此文件夹下。

二、组件引入和使用

我们的所有页面一般写在pages目录下,每个页面有wxml,wxss,js,json四个文件,在需要使用组件的页面.json文件中,引入

{
  "usingComponents": {
    "componentA": "../../components/child1/child1"
  }
}

在.wxml中使用

<view>
    <view>微信小程序组件传参</view>
    <componentA />
</view>

三、子组件触发父组件事件

父组件.wxml:
<component bind:myevent="onMyEvent"/>
使用bind:自定义触发事件
父组件.js

onMyEvent:function(e){
      // 事件处理,比如对data赋值操作
}

子组件.js
this.triggerEvent('myevent') // 触发父组件方法
若要传值:
子组件.js
this.triggerEvent('myevent', {key: value}) // 传值
父组件:

onMyEvent:function(e){
      e.detail.key // 获取到传过来的值
}

四、父组件向子组件传值

父组件.wxml
<component key="{{value}}"/>

data: {
	value: '1111'
}

key为子组件中 properties自定义的值,value为父组件中data定义的值
子组件.js

	properties: {
	    key: {
	      type: String
	    }
  },

子组件.wxml
<view>{{key}}</view>

猜你喜欢

转载自blog.csdn.net/qq_41927909/article/details/82990007