微信小程序底部彈出層組件與slot插槽

參考:
組件樣式隔離

組件wxml的slot

bottom-modal組件

在這裏插入圖片描述
bottom-modal.wxml

<!--components/bottom-modal/bottom-modal.wxml-->
<view class="modal" hidden="{{!modalShow}}">
<view>
</view>
  <view class="panel">
      <i class="iconfont icon-shanchu1" bind:tap="onClose"></i>

  </view>
</view>

bottom-modal.wxss

.modal {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 99;
  text-align: center;
  background: rgba(0, 0, 0, 0.6);
}

.panel {
  position: absolute;
  bottom: 0rpx;
  left: 0;
  width: 100%;
  min-height: 300rpx;
  box-sizing: border-box;
  background-color: #f8f8f8;
}

/* 可以直接對外部樣式修改 */

.modal .icon-shanchu1 {
  position: absolute;
  right: 10rpx;
  top: 10rpx;
  padding: 20rpx; /* 爲了增加點擊區域大小 */
}

bottom-modal.js

// components/bottom-modal/bottom-modal.js
Component({
  properties: {
    modalShow: Boolean
  },
  options: {
    styleIsolation: 'apply-shared'
  },
 
  data: {

  },

  methods: {
    onClose() {
      this.setData({
        modalShow: false,
      })
    },
  }
})

引入組件

在demo.json中引入組件

{
  "usingComponents": {
    "x-bottom-modal": "/components/bottom-modal/bottom-modal"
  }
}

demo.wxml

<view>
  <view class="publish-container" bind:tap="onPublish">
    <i class="iconfont icon-fabu"></i>
  </view>
  <view>
    <x-bottom-modal modalShow="{{modalShow}}" />
  </view>
</view>

demo.js

Page({
  data: {
    // 控制底部彈出層是否顯示
    modalShow: false,
  },

  // 發佈功能
  onPublish() {
    this.setData({
      modalShow: true,
    })
  },

  onLoad: function(options) {

  },

})

組件樣式隔離

在項目的根目錄中新增了iconfont.wxss,iconfont.wxss裏面是項目中使用小圖標。
在這裏插入圖片描述
在app.wxss中import 導入iconfont.wxss文件,這樣項目中就可以使用iconfont.wxss中的圖標了
在這裏插入圖片描述

但是組件中使用iconfont.wxss會存在組件樣式隔離的問題。

如下是bottom-modal組件中使用iconfont.wxss中的圖標:
在這裏插入圖片描述
在bottom-modal組件中使用了外部的iconfont.wxss屬性,需要對組件樣式隔離進行處理。

  • isolated 表示啓用樣式隔離,在自定義組件內外,使用 class 指定的樣式將不會相互影響(一般情況下的默認值);
  • apply-shared 表示頁面 wxss 樣式將影響到自定義組件,但自定義組件 wxss 中指定的樣式不會影響頁面;
  • shared 表示頁面 wxss 樣式將影響到自定義組件,自定義組件 wxss 中指定的樣式也會影響頁面和其他設置了 apply-shared 或 shared 的自定義組件。(這個選項在插件中不可用。)
    在這裏插入圖片描述
  options: {
    styleIsolation: 'apply-shared'
  },

控制彈出層顯示和隱藏

在這裏插入圖片描述
點擊發布按鈕,顯示底部彈出層;點擊關閉按鈕,關閉底部彈出層。

在這裏插入圖片描述
使用modalShow控制顯示和隱藏,modalShow = true時顯示。

在demo.js中設置了onPublish方法,當點擊發布按鈕時,modalShow = true,顯示彈出層。
在這裏插入圖片描述
在bottom-modal組件中設置onClose方法,當點擊關閉按鈕時,modalShow = false,隱藏彈出層。
在這裏插入圖片描述

組件wxml的slot插槽

在組件的wxml中可以包含 slot 節點,用於承載組件使用者提供的wxml結構。

默認情況下,一個組件的wxml中只能有一個slot。需要使用多slot時,可以在組件js中聲明啓用。

在這裏插入圖片描述

在bottom-modal組件的js中添加 multipleSlots: true
在這裏插入圖片描述
在bottom-modal組件的wxml中添加兩個具名插槽
在這裏插入圖片描述

    <!-- slot插槽  具名插槽-->
    <slot name="slot1"></slot>
    <slot name="slot2"></slot>

在demo.wxml中使用具名插槽
在這裏插入圖片描述
效果如下:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章