您现在的位置是:亿华云 > IT科技
前端:Uniapp封装组件用法
亿华云2025-10-09 01:17:42【IT科技】5人已围观
简介大家在做前端项目开发的时候,经常会遇到公用的一些页面,比如搜索、列表、商品详情卡片、评论列表等。为了提高开发效率、使代码看起来更加简洁,这个时候封装相应的组件是最好的解决方案。今天小编给大家介绍一下如
大家在做前端项目开发的前端时候,经常会遇到公用的封装一些页面,比如搜索、组件列表、用法商品详情卡片、前端评论列表等。封装为了提高开发效率、组件使代码看起来更加简洁,用法这个时候封装相应的前端组件是最好的高防服务器解决方案。今天小编给大家介绍一下如何在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>个人博客网站:https://programmerblog.xyz
站群服务器很赞哦!(276)