微信小程序---父子组件间传值

父子组件传值分为父传子和子传父两种情况

1.父传子(直接传)
2.子传父(父亲需要问一下)

首先需要有父组件与子组件两个组件

1父组件为正常页面,
在这里插入图片描述
2子组件要放到components文件夹里面,
在这里插入图片描述

3其次要在父组件的.json文件中注册子组件信息:

"usingComponents": {
    "child":"../components/child/child"
    //名字:地址
  }

4然后再父组件的.wxml文件中写子组件的出口<child></child>
要与上面注册的名字相同

<!--pages/first/first.wxml-->
<text>父组件</text>
<view>
  <child></child>
</view>
<!--pages/components/child.wxml-->
<text>子组件</text>

在这里插入图片描述

一、父传子

1在父组件中的子组件标签上绑定msg

<!--pages/first/first.wxml-->
<text>父组件</text>
<view>
  <child msg="父组件传的值"></child>
</view>

2可以在child.js文件里设置一下默认值

// pages/components/child.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    msg:{type:String,value:"默认值"}
  },

3子组件里面显示

<!--pages/components/child.wxml-->
<text>子组件</text>
<view><text>{{msg}}</text></view>

在这里插入图片描述

二、子传父

1,在子组件的js文件里的methods里写一个传值的方法

  /**
   * 组件的方法列表
   */
  methods: {
    childfn(){
      this.triggerEvent("customevent","子组件传过来的值");
    }
  }

2在子组件的.wxml文件里写一个按钮进行触发传值事件

<!--pages/components/child.wxml-->
<text>子组件</text>
<view>
  <text>{{msg}}</text>
  <button bindtap="childfn">点击传值</button>
</view>

3在父组件的子组件标签里bind绑定子组件的传值的名字(customevent),并且用一个方法接收(fn)

<!--pages/first/first.wxml-->
<text>父组件</text>
<view>
  <child msg="父组件传的值" bindcustomevent="fn"></child>
  {{childmsg}}
</view>

4在父组件的js文件里写接收值的方法

fn(e){
      //console.log(e)
      this.setData({
          childmsg:e.detail
      })
  },

点击前
在这里插入图片描述
点击后
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值