微信小程序自定义组件

微信小程序自定义组件

一. 建立自定义组件

相似于页面,一个自定义组件由 json wxml wxss js 4个文件组成css

二.组件声明

首先须要在自定义组件所在的 json 文件中进行自定义组件声明html

{
  "component": true
}

三.编辑组件

同时,还要在 wxml 文件中编写组件模板,在 wxss 文件中加入组件样式python

wxml与xcss和普通页面设置差很少json

wxml小程序

<!-- 这是自定义组件的内部WXML结构 -->
<view class="inner">
  {{innerText}}
    <slot></slot>
</view>

xcss微信小程序

/* 这里的样式只应用于这个自定义组件 */
.inner {
  color: red;
}

js文件设置有点区别微信

Component({
  properties: {
    // 这里定义了innerText属性,属性值能够在组件使用时指定
    innerText: {
      type: String,
      value: 'default value',
    }
  },
  data: {
    // 这里是一些组件内部数据
    someData: {}
  },
  methods: {
    // 这里是一个自定义方法,方法必须写在methods内
    customMethod: function(){}
  }
})

四.再使用该组件的组件页面

首先要在页面的 json 文件中进行引用声明。还要提供对应的组件名和组件路径xss

// 引用声明
  "usingComponents": {
    // 要使用的组件的名称     // 组件的路径
    "component-tag-name": "path/to/the/custom/component"
  }
}

组件的使用和Vue同样,this

在wxml文件中code

<component-tag-name></component-tag-name>

五.父组件中显示子组件内的变量

父组件的wxml页面传输值

<component-tag-name></component-tag-name>

子组件的wxml

<view>{{变量名}}</view>

让父组件内显示子组件的内容

#在组件中
   properties: {
    变量名:{
      type:String,
      value:"变量值"
    }
  }
//而不是把变量名放在data中

六.触发子组件的事件时候触发父组件的事件

父组件页面

页面
 <component-tag-name bind:icre="icre"></component-tag-name>

父组件的js

页面中js
  icre:function(e){
    console.log(e)
    this.setData({
        num:this.data.num+1
    })
  },

子组件页面

<button bindtap='clickpush'>加我</button>

子组件的js

clickpush:function(e){
      console.log(e)
      this.triggerEvent("icre",{"index":13},{})
    }
相关文章
相关标签/搜索