微信小程序子父组件之间传值 和 插槽 slot

父组件向子组件传值

自定义组件Nav,在父组件中注册并使用

在组件标签上自定义属性 hello和name

<Nav hello="{
   
   {arrs}}" name="navs"></Nav>

arrs在父组件中的数据

 data: {
    arrs:[
      {
        id:0,
        title:'足球'
      },
      {
        id:1,
        title:'篮球'
      },
      {
        id:2,
        title:'排球'
      },
      {
        id:3,
        title:'乒乓球'
      },
      {
        id:4,
        title:'羽毛球'
      }
    ],
}

将自定义的属性注册在子组件Nav的properties 中注册

properties: {
    name:{
      type:String,
      value:''
    },
    hello:{
        type:Array,
        value:[]
    }
  },
}

 子组件模板中直接渲染数组

<view class="tencentNews-nav">
  <view 
  wx:for="{
   
   {hello}}" 
  wx:key="id"
  bindtap="click2"
  data-index="{
   
   {index}}"
  class="{
   
   {idx2 == index ? 'active' : ''}}"
  >{
   
   {item.title}}</view>
</view>
<view>{
   
   {name}}</view>

子组件向父组件传值

创建自定义子组件MyBtn 在父组件中注册并使用

子组件定义事件click

<view>
  <button type="primary" bindtap="click">子组件传父组件</button>
</view>

 MyBtn .js

methods: {
    click:function(){
      console.log("__________")
      //自定义一个事件 第一个参数 事件名 第二个参数 是传递的数据
      this.triggerEvent('myClick',{
        'name':'小程序',
        'age':'5'
      })
    }
  }

父组件中渲染

<MyBtn bindmyClick="hello"></MyBtn>
<view>
  {
   
   {name}}{
   
   {age}}
</view>

父组件中js

data: {
    name:'',
    age:''
},
hello:function(e){
    console.log('---父组件中-------')
    console.log(e.detail)
     //获取子组件传递的数据
    var datas = e.detail
    this.setData({
      name:datas.name,
      age:datas.age
    })
  },

子组件传值给父组件,在自定义组件中以事件的形式传递 triggerEvent 自定义事件。在父组件中 以组件标签的形式调用组件 将自定义事件绑定在这个组件标签上

小程序插槽slot

插槽 占位符 在自定义组件中,标签内容的获取,使用slot组件

父组件wxml

<MyBtn bindmyClick="hello">
  <view>小程序中slot</view>
</MyBtn>

子组件

<view>
  <slot></slot>
</view>

猜你喜欢

转载自blog.csdn.net/weixin_41040445/article/details/114480841
今日推荐