How does the WeChat applet transfer value?

1. Passing from parent to child
Description:
Pass the value through custom properties in the parent component, accept it through the properties property in the child component js file, set the default value, and finally render it directly in the child component.

1. Declare the reference to the child component in the json file of the parent component

// parents.json
{
  "usingComponents": {
    "w-child": "/components/children/children"
  }
}

2. Use child components in the wxml of the parent component

<w-child fatherName='mike fatherage='25'></w-child>

3. The child component obtains the value passed from the parent component in js.
Properties is the external property of the component, which is a mapping table from property name to property setting. The property setting can contain three fields, type represents the attribute type, and value represents the initial property. Value, observer represents the response function when the attribute value is changed

// child.js
properties: {  // 在这里拿到了数据之后可以直接使用了(在wxml模板渲染,或者js中使用this.data.fatherName/this.properties.fatherName 都能获取到),不要直接修改properties属性中的数据
  fatherName: {
    type: String
  },
  fatherage: Number
}


2. The
main implementation principle of the child component passing value to the parent component (this.triggerEvent() ) : the event publishing and subscription method (also known as the observer mode)
is defined in the child component through this.triggerEvent(' method of dispatch ','Data to be transferred') to transfer data [similar to this.$emit]
In the parent component, pass bindconfirm="method name" (getConfirmData), and then there is a data parameter in the getConfirmData method, which is passed over value

1. The child component triggers a custom event and passes data to the parent component

<!-- child.wxml-->
<view class="nav" data-index="0" bindtap="onChangeValue">tab</view>

2. The child component actively triggers a custom event in the click event

// child.js
onChangeValue(e) {
      var index = e.target.dataset.index      
      //子组件传值给父组件
      let detail = { // 需要传递什么数据就在这个对象中写
        val: index
      }
      // detail 对象,提供给事件监听函数的参数数据
      // changeIndex 是自定义名称事件,父组件中监听使用
      this.triggerEvent('changeIndex', myEventDetail)
    }

3. The custom event of the child component is monitored in the parent component wxml

<!-- parents.wxml-->
<!-- 注意这里写的事件监听名字-->
 <w-child bind:changeIndex="getIndex" />

4. Add an event function to the js of the parent component to get the data passed by the child component

// parents.js
  getIndex( data) { // paramData参数就是子组件的this.triggerEvent()
    console.log(data.detail.val)  // 0
  }

Guess you like

Origin blog.csdn.net/lqlq54321/article/details/106930079