微信小程序公共组件封装,父子组件之间相互传值和相互调用方法


1.微信小程序公共组件封装

由于有些页面上会出现重复的代码,就需要把它提炼成组件的形式,方便后期的应用,也可以提高开发效率,接下来我就把上一篇文章里做过的一个简单的顶部导航菜单封装成公共的组件。

上一篇文章的链接:https://www.cnblogs.com/wxhcode/p/14319712.html

:子组件需要的样式也在上一篇文章的链接当中

1.1. 创建组件

首先在components中新建一个文件夹,在此文件夹上右击选择新建component选项,建好的目录结构如下

1.2  在子组件topnav.wxml里面写入标签



    for="{{menuList}}" wx:key="index" bindtap="selectCurr" data-id="{{item.id}}">
        {{item.name}}
        
    

1.3  在父页面的json文件里注册组件

{
  "usingComponents": {
    "topNav": "/components/topNav/topnav"
  }
}

·1.4  在父页面上应用组件,并给子组件传入需要的值



    
    

2.父页面给子组件传值

2.1 将父页面的data里面定义的 menuList数组 以 menuList="{{menuList}}" 的方式传给子组件

  data: {
    menuList:[  //菜单列表
      {id:0,name:'所有课程'},
      {id:1,name:'学习中'},
      {id:2,name:'未读课程'}
    ],
  },

2.2 在子组件的 propertiesl里面接收传过的值,并设置默认值

  properties: {
    menuList:{
      type:Array,
      value:[]
    },
  },

3.子组件调用父页面的方法

3.1 在应用子组件的时候可以 用 bind:getList='getList'  将页面的getList方法传给子组件,如上述1.4的代码所示

3.2 在子组件中可以用  this.triggerEvent('getList', '123') 的方式调用,默认只能传一个参数,如果需要传多个参数,则需要定义一个对象,将这个对象作为整个参数传过去

子组件js的详细代码如下:

Component({
  /**
   * 组件的属性列表
   */
  options: {
    addGlobalClass: true,  //采用全局样式
  },
  properties: {
    menuList:{
      type:Array,
      value:[]
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    hasindex:0, //当前选择菜单的id
  },
  /**
   * 组件的方法列表
   */
  methods: {
      // 选择菜单
      selectCurr(e){
          this.setData({hasindex:e.currentTarget.dataset.id});
          let temp =  {
            id :'1',
            name : '2'
          }
          this.triggerEvent('getList', temp);
      },
      getover(){
        console.log("over");
      }
  }
})

3.3 在父页面js文件的 getList方法中输出传过来的参数

  // 获取课程内容   getList(temp){     console.log(temp.detail);   },

输出结果如下:

4.父页面调用子组件的方法

4.1 在父页面应用子组件的时候,给子组件一个id



    
    

4.2 在父页面的js文件中用  selectComponent  调用子组件的 getover 方法

  onLoad: function (options) {
    this.selectComponent('#topNav').getover();
  },