
大家在做前端项目开发的时候,经常会遇到公用的一些页面,比如搜索、列表、商品详情卡片、评论列表等。为了提高开发效率、使代码看起来更加简洁,这个时候封装相应的组件是最好的解决方案。今天小编给大家介绍一下如何在uniapp中封装组件,希望对大家能有所帮助!
1、在components目录新建card.vue 组件
- <template>
- <viewclass="list"v-for="iteminresData">
- <viewclass="item"@tap="$toPage(item.url)">
- <viewclass="titletext-ellipsis">{{item.title}}</view>
- <viewclass="contentflex-row">
- <viewclass="info">
- <viewclass="summary">{{item.digest}}</view>
- <viewclass="flex-row">
- <textclass="date">{{item.publishDate}}</text>
- <textclass="views">{{item.viewCount}}阅读</text>
- </view>
- </view>
- <viewclass="cover">
- <imageclass="img":src="item.imgUrl"></image>
- </view>
- </view>
- </view>
- </view>
- </template>
- <script>
- exportdefault{
- propsData:{
- resData:[]/*接收传递的参数*/
- }
- }
- </script>
- <stylelang="scss"scoped>
- .item{
- padding:30rpx;
- margin-bottom:30rpx;
- background-color:#FFF;
- .title{
- font-weight:bold;
- padding-bottom:30rpx;
- border-bottom:2rpxsolid#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;
- @includetext-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>
- <viewclass="container">
- <!--组件引用-->
- <card:resData="backendData"></card>
- </view>
- </template>
- <script>
- exportdefault{
- data(){
- return{
- backendData:[]
- }
- },
- onLoad(){
- this.initData();
- },
- methods:{
- asyncinitData(){
- //通过请求获取数据给页面的数据赋值
- this.backendData=res.data.list;
- }
- }
- }
- </script>
- <stylelang="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>
- importcardfrom'@/components/card/card.vue'//1.vue方式导入组件
- exportdefault{components:{card}//2.vue方式注册组件
- </script>
个人博客网站:https://programmerblog.xyz
原文链接:https://mp.weixin.qq.com/s/vfJga-rc3Gt-9FNy5ZD6Ow








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。