微信小程序自定义组件

在微信小程序中,可能出现很多类似的地方,这就可以用到自定义组件,来进行操作。

下边是自定义组件的方法

创建一个文件夹,在这个文件夹下面右键新建一个Component,然后会生成四个文件夹【如果定义自定义组件需用这个新建Component】

 2、四个文件夹的用处

 组件的样式

样式的隔离【styleIsolation:"参数",

样式隔离:apply-shared 父组件影响子组件,shared父子相互影响, isolated相互隔离

  // 选项:

  options:{

    // 样式隔离:apply-shared 父影响子,shared父子相互影响, isolated相互隔离

    styleIsolation:"isolated",

    // 允许多个插槽

    multipleSlots:true,

  },

外部类【可以在父组件里边修改子组件样式】

externalClasses:["类名a"]

<view class="类名a">我是子组件里边的view</view>

在父页面wxml中使用

<cell cell-class="类名a"></cell>
在父页面的wxss中使用

.类名a{
  line-height: 120rpx !important;
  color:#F70;
}

 组件插槽

默认插槽

父组件

<cell>
      <text>插槽内容</text>
</cell>

子组件

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

命名多插槽

父组件

 <cell>
    <text slot="pre"> 一条</text>
    <text slot="next">二两</text>
</cell>

子组件

//先在js定义这个

options:{ multipleSlots:true}

在页面用这个

<view>
    <slot name="pre"></slot>
    <slot name="next"></slot>
</view>

组件传参

//父传子组件

property

 properties: {
    title:{
      type:String,
      value:""
    },
    num:{
      // 定了类型
      type:Number,
      //定义默认值
      value:1
    }
  },

//子传父

triggerEvent

  methods: {
      itemclick(e){
        console.log(e);    
        //发送一个事件 
        this.triggerEvent("itemclick",e.detail)
      }
  }

组件使用

  •  定义组件(js,wxml,json,wxss)
  • 页面的 xxx.json  
     usingComponent 注册

"usingComponents": {
"cell":"/components/cell/cell",
"item":"/components/item/item"
}

  • 使用组件

<cell></cell>
<item></item>

自定义组件Component

  • 生命周期  lifetimes
  • data 数据
  • methods 方法
  • properties 属性(只读)
  • externalClasses 外部类
  • options选项

multipleSlots:true 多个插槽

 styleIsolation:"isolated" 组件的样式格式

定义组件item

  • props

title标题

icon 图标

tip 提示

url 跳转连接

open-type 打开的方式

  •  slot

right

left插槽

  •  event

click事件

  • 外部类

itemClass 整体

titleClass 标题

自定义组件生命周期

组件的生命周期   lifetimes

created  创建【此时还不能调用 setData】

attached  挂载

detached  卸载

页面的生命周期  pageLifetimes

show 显示

hide 后台运行

resize 尺寸变化

写自定义导航栏

 wx.getMenuButtonBoundingClientRect()  胶囊的边界

wx.getSystemInfoSync();  系统信息(状态栏的高度)

{
  "usingComponents": {
    "nav":"/components/nav/nav"
  },
  "navigationStyle":"custom"
}

配置自定义状态栏

  lifetimes:{
    attached(){
      // 获取系统信息
     var info =  wx.getSystemInfoSync();
     console.log(info);
    //  更新状态栏的高度
     this.setData({statusBarHeight:info.statusBarHeight})
    //  胶囊的位置
    const res = wx.getMenuButtonBoundingClientRect()
    console.log(res);
    // 标题栏可以使用的宽度(排除右侧胶囊的位置)
    this.setData({titleWidth:res.left});
    // 标题栏高度
    var barHeight = res.height+(res.top-info.statusBarHeight)*2;
    this.setData({barHeight});

    // 获取当前页
    var pages = getCurrentPages();
    console.log(pages);
    //更新页面的长度
    this.setData({pagesLen:pages.length})
    }
  },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值