微信小程序中组件的使用

微信小程序中组件的使用:

微信小程序中组件定义在项目根目录下components文件夹下,在页面使用的时候需要在页面的json文件中声明,如
请添加图片描述
父组件向子组件传值及子组件向父组件传值:

父组件wxml中:通过属性绑定值的方式向子组件传值,通过自定义事件接收子传递过来的值

<!-- 父组件向子组件传值:和vue或uni-app相同,title='连接WiFi' -->
<header title='连接WiFi' bindEmitheadClick='bindEmitheadClickHandle'></header>

子组件wxml中: 通过{ {}}方式显示父组件中接收到的值,用事件触发triggerEvent方法向父组件传值

<!-- 通过headClickHandle函数触发triggerEvent向父组件发送消息 -->
<view class='header' bindtap='headClickHandle'>{
   
   {title}}</view>

子组件js:通过properties接收父组件传过来的值,通过triggerEvent向父组件发送消息,类似emit()

// 组件使用Component声明
Component({
    
    
//  properties:用来接收父组件传递的内容,类似vue中props
  properties: {
    
    
    title: {
    
    
      type: String,
      value: '默认标题'
    }
  },
  data: {
    
    

  },
  // 组件中的方法可以定义在methods中
  methods: {
    
    
    headClickHandle () {
    
    
      console.log('子组件点击了')
      // 子组件向父组件传值:triggerEvent,类似vue或uni-app中的this.emit()
      this.triggerEvent('EmitheadClick', {
    
    name:'jack',age:18})
    }
  },
  // 微信小程序组件中的生命周期函数可以直接写在Component中的一级对象中,还可以写在lifetimes中的节点下,这种方式是推荐的
  lifetimes: {
    
    
    // created 组件首次创建时触发,进入每个使用该组件的页面后只加载一次
    created () {
    
    
      console.log('组件被创建了')
    },
    // ready 组件试图加载完后执行,也是只只执行一次
    ready () {
    
    
      console.log('ready')
    },
    // moved 组件位置发生改变时触发
    moved () {
    
    
      console.log('moved')
    },
    // 组件进入页面时触发,只触发一次
    attached () {
    
    
      console.log('attached')
    }
  },
  // 组件被页面移出时触发
  detached () {
    
    
    console.log('组件被卸载了')
  },
  // error 组件抛出异常是触发
  error () {
    
    
    console.log('error')
  }
})

提示:本文图片等素材来源于网络,若有侵权,请发邮件至邮箱:[email protected]联系笔者删除。
笔者:苦海

猜你喜欢

转载自blog.csdn.net/weixin_46758988/article/details/128123738