前端:Uniapp封裝組件用法
大家在做前端項(xiàng)目開(kāi)發(fā)的時(shí)候,經(jīng)常會(huì)遇到公用的一些頁(yè)面,比如搜索、列表、商品詳情卡片、評(píng)論列表等。為了提高開(kāi)發(fā)效率、使代碼看起來(lái)更加簡(jiǎn)潔,這個(gè)時(shí)候封裝相應(yīng)的組件是最好的解決方案。今天小編給大家介紹一下如何在uniapp中封裝組件,希望對(duì)大家能有所幫助!
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:[] /*接收傳遞的參數(shù)*/
- }
- }
- </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 頁(yè)面
- <template>
- <view class="container">
- <!--組件引用-->
- <card :resData="backendData" ></card>
- </view>
- </template>
- <script>
- export default {
- data() {
- return {
- backendData: []
- }
- },
- onLoad() {
- this.initData();
- },
- methods: {
- async initData() {
- //通過(guò)請(qǐng)求獲取數(shù)據(jù)給頁(yè)面的數(shù)據(jù)賦值
- this.backendData = res.data.list;
- }
- }
- }
- </script>
- <style lang="scss" scoped>
- </style>
3、組件引用方式
1)、全局注冊(cè)方式 main.js直接導(dǎo)入,每個(gè)頁(yè)面都可以直接調(diào)用
import card from './components/card/card.vue'
Vue.component('card',card)
2)、局部注冊(cè)方式
通過(guò)uniapp的easycom可以簡(jiǎn)化組件的引用,如果你創(chuàng)建的組件在components目錄下,符合 components/組件名稱/組件名稱.vue 目錄結(jié)構(gòu),就可以在頁(yè)面直接使用,不需要在單獨(dú)引用組件。uniapp默認(rèn)是開(kāi)啟easycom配置的。所以可以直接使用。
傳統(tǒng)的引用方式:
- <script>
- import cardfrom'@/components/card/card.vue' //1.vue方式導(dǎo)入組件
- exportdefault{ components:{card} //2.vue 方式注冊(cè)組件
- </script>
個(gè)人博客網(wǎng)站:https://programmerblog.xyz