微信小程式自定義元件
阿新 • • 發佈:2022-03-10
當微信小程式裡面的一個模組需要重複使用時,就可以使用自定義元件的方式,以後在使用這一模組時可以隨時呼叫,不用再寫重複的程式碼。比如下面的搜尋框可能在多個頁面都會出現,這時我們就可以使用自定義元件的方式。
1.首先建立一個資料夾components,再建立一個存放元件的資料夾,之後右鍵單擊選擇新建Component。
2.資料夾裡同樣是包含js json wxml和wxss檔案,寫元件的方式和微信小程式普通頁面是相同的,比如我實現了上面搜尋框的元件,程式碼如下:
SearchInput.wxml
<view class="search_input"><navigator url="/pages/search/search" open-type="navigate">搜尋</navigator> </view>
SearchInput.wxss
.search_input { height: 90rpx; padding: 10rpx; background-color: var(--themeColor); } .search_input navigator { height: 100%; display: flex; justify-content: center; align-items: center; background-color: #fff; border-radius: 15rpx; color: #666; }
3.引入元件,比如在分類頁面category上引入這個元件,就在json檔案中引入元件
category.json
{ "usingComponents": { "SearchInput":"../../components/SearchInput/SearchInput" }, "navigationBarTitleText": "商品分類" }
category.wxml
<view class="cates"> <SearchInput></SearchInput> </view>
這樣就可以多個頁面都呼叫這個元件,避免程式碼的重複。