小程序页面和组件相互传参

首先,要知道的一个潜规则:页面中写事件,组件内不写事件。

一、父传子(页面向组件传递参数)

1.页面wxml:

/* 引用组件 */
<toast list='{
   
   {list}}'></toast>

  第一个list是组件接收参数,第二个list是你要传入的值

2.子组件接收:

        

/**
 * 组件的属性列表
 */
 properties: {
   list: {
     type: Object,
     value: {}
  }
},

  type是参数类型,例如:(arrary,number,string,function,object) value没有值则为空

二、子传父(组件向页面传递参数)

1.子组件:

<view class="btn-confirm" bindtap="onConfirm" data-index="{
   
   {list.index}}">{
   
   {list.confirmText}}</view>

    

/**
 * 子组件向父组件传值
 */
onConfirm: function (e) {
   const index = e.currentTarget.dataset.index
   // confirm为父组件接收的事件名
   this.triggerEvent('confirm', {index})
}

2.页面接收组件传入的值:

// bind:confirm bind后面必须跟组件那边起的名称
<toast list='{
   
   {list}}' bind:confirm='confirm'></toast>

 js:

// 接收子组件传递过来的参数
confirm(e) {
    // 打印传的值
    console.log(e.detail)
},

三、如果不成功

1.检查页面json引用组件路径是否正确

{
  "usingComponents": {
    "toast": "/components/toast/index",
  }
}

 2.检查json的component是否为true

{
    "component": true
}

猜你喜欢

转载自blog.csdn.net/m0_71349739/article/details/128531553