当前位置:首页 > 通信资讯 > 正文

uniapp怎么封装组件(uniapp封装接口)

uniapp怎么封装组件(uniapp封装接口)

大家在做前端项目开发的时候,经常会遇到公用的一些页面,比如搜索、列表、商品详情卡片、评论列表等。为了提高开发效率、使代码看起来更加简洁,这个时候封装相应的组件是最好的解决方案。今天小编给大家介绍一下如何在uniapp中封装组件,希望对大家能有所帮助!

1、在components目录新建card.vue 组件

  1. <template>
  2. <viewclass="list"v-for="iteminresData">
  3. <viewclass="item"@tap="$toPage(item.url)">
  4. <viewclass="titletext-ellipsis">{{item.title}}</view>
  5. <viewclass="contentflex-row">
  6. <viewclass="info">
  7. <viewclass="summary">{{item.digest}}</view>
  8. <viewclass="flex-row">
  9. <textclass="date">{{item.publishDate}}</text>
  10. <textclass="views">{{item.viewCount}}阅读</text>
  11. </view>
  12. </view>
  13. <viewclass="cover">
  14. <imageclass="img":src="item.imgUrl"></image>
  15. </view>
  16. </view>
  17. </view>
  18. </view>
  19. </template>
  20. <script>
  21. exportdefault{
  22. propsData:{
  23. resData:[]/*接收传递的参数*/
  24. }
  25. }
  26. </script>
  27. <stylelang="scss"scoped>
  28. .item{
  29. padding:30rpx;
  30. margin-bottom:30rpx;
  31. background-color:#FFF;
  32. .title{
  33. font-weight:bold;
  34. padding-bottom:30rpx;
  35. border-bottom:2rpxsolid#F5F5F5;
  36. }
  37. .content{
  38. padding-top:30rpx;
  39. align-items:flex-start;
  40. .info{
  41. width:calc(100%-160rpx);
  42. .summary{
  43. color:#777;
  44. height:80rpx;
  45. font-size:24rpx;
  46. line-height:1.6;
  47. margin-bottom:10rpx;
  48. @includetext-ellipsis(2);
  49. }
  50. .date{
  51. font-size:24rpx;
  52. color:$main-color;
  53. opacity:0.6;
  54. }
  55. .views{
  56. color:#999;
  57. font-size:24rpx;
  58. }
  59. }
  60. .cover{
  61. width:140rpx;
  62. height:120rpx;
  63. .img{
  64. width:100%;
  65. height:100%;
  66. border-radius:4rpx;
  67. }
  68. }
  69. }
  70. }
  71. </style>

2、新建index.vue 页面

  1. <template>
  2. <viewclass="container">
  3. <!--组件引用-->
  4. <card:resData="backendData"></card>
  5. </view>
  6. </template>
  7. <script>
  8. exportdefault{
  9. data(){
  10. return{
  11. backendData:[]
  12. }
  13. },
  14. onLoad(){
  15. this.initData();
  16. },
  17. methods:{
  18. asyncinitData(){
  19. //通过请求获取数据给页面的数据赋值
  20. this.backendData=res.data.list;
  21. }
  22. }
  23. }
  24. </script>
  25. <stylelang="scss"scoped>
  26. </style>

3、组件引用方式

1)、全局注册方式 main.js直接导入,每个页面都可以直接调用

import card from './components/card/card.vue'

Vue.component('card',card)

2)、局部注册方式

通过uniapp的easycom可以简化组件的引用,如果你创建的组件在components目录下,符合 components/组件名称/组件名称.vue 目录结构,就可以在页面直接使用,不需要在单独引用组件。uniapp默认是开启easycom配置的。所以可以直接使用。

传统的引用方式:

  1. <script>
  2. importcardfrom'@/components/card/card.vue'//1.vue方式导入组件
  3. exportdefault{components:{card}//2.vue方式注册组件
  4. </script>

个人博客网站:https://programmerblog.xyz

原文链接:https://mp.weixin.qq.com/s/vfJga-rc3Gt-9FNy5ZD6Ow

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

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