Use of components in WeChat applets

Use of components in WeChat applets:

The components in the WeChat applet are defined in the components folder under the project root directory. When using the page, they need to be declared in the json file of the page, such as passing values ​​from the parent component to the child component and from the child component to the parent component
Please add a picture description
:

In the parent component wxml: pass the value to the child component through the property binding value, and receive the value passed by the child through the custom event

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

In the child component wxml: display the value received in the parent component through { {}}, and use the event trigger triggerEvent method to pass the value to the parent component

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

Child component js: Receive the value passed by the parent component through properties, and send a message to the parent component through triggerEvent, similar to 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')
  }
})

Tips: The pictures and other materials in this article come from the Internet. If there is any infringement, please send an email to the mailbox: [email protected] to contact the author to delete it.
Author: sea of ​​bitterness

Guess you like

Origin blog.csdn.net/weixin_46758988/article/details/128123738