大家在做前端項目開發的時候,經常會遇到公用的一些頁面,比如搜索、列表、商品詳情卡片、評論列表等。為了提高開發效率、使代碼看起來更加簡潔,這個時候封裝相應的組件是最好的解決方案。今天小編給大家介紹一下如何在uniapp中封裝組件,希望對大家能有所幫助!
1、在components目錄新建card.vue 組件
<template> <view class="list"v-for="item in resData"><view class="item" @tap="$toPage(item.url)"><view class="title text-ellipsis">{{item.title}}</view><view class="content flex-row"><view class="info"><view class="summary">{{item.digest}}</view><view class="flex-row"><text class="date">{{item.publishDate}}</text><text class="views">{{item.viewCount}} 閱讀</text></view></view><view class="cover"><image class="img" :src="item.imgUrl"></image></view></view></view> </view>
</template><script>export default {propsData:{resData:[] /*接收傳遞的參數*/}}
</script><style lang="scss" scoped>
.item{padding: 30rpx;margin-bottom: 30rpx;background-color: #FFF;.title{font-weight: bold;padding-bottom: 30rpx;border-bottom: 2rpx solid #F5F5F5;}.content{padding-top: 30rpx;align-items: flex-start;.info{width: calc(100% - 160rpx);.summary{color: #777;height: 80rpx;font-size: 24rpx;line-height: 1.6;margin-bottom: 10rpx;@include text-ellipsis(2);}.date{font-size: 24rpx;color: $main-color;opacity: 0.6;}.views{color: #999;font-size: 24rpx;}}.cover{width: 140rpx;height: 120rpx;.img{width: 100%;height: 100%;border-radius: 4rpx;}}}
}
</style>
2、新建index.vue 頁面
<template><view class="container"><!--組件引用--><card :resData="backendData" ></card> </view>
</template><script>export default {data() {return {backendData: []}},onLoad() {this.initData();},methods: {async initData() {//通過請求獲取數據給頁面的數據賦值 this.backendData = res.data.list; }}}
</script><style lang="scss" scoped>
</style>
3、組件引用方式
1、全局注冊方式 main.js直接導入,每個頁面都可以直接調用
import card from './components/card/card.vue'
Vue.component('card',card)
2、局部注冊方式
通過uniapp的easycom可以簡化組件的引用,如果你創建的組件在components目錄下,符合 components/組件名稱/組件名稱.vue 目錄結構,就可以在頁面直接使用,不需要在單獨引用組件。uniapp默認是開啟easycom配置的。所以可以直接使用。
傳統的引用方式:
<script>
import cardfrom'@/components/card/card.vue' //1.vue方式導入組件
exportdefault{ components:{card} //2.vue 方式注冊組件
</script>
IT技術分享社區
個人博客網站:https://programmerblog.xyz
文章推薦程序員效率:畫流程圖常用的工具程序員效率:整理常用的在線筆記軟件遠程辦公:常用的遠程協助軟件,你都知道嗎?51單片機程序下載、ISP及串口基礎知識硬件:斷路器、接觸器、繼電器基礎知識