微信小程序中的组件使用2

需求

  

上面两个页面是同一个小程序的不同页面,两个页面中都是用到了label,有相似的地方,但是也有不同之处,这个时候,如果我们想要将这些label做出组件,然后复用,有该怎么做呢?

基础组件

首先在components下面新建tag文件夹,用来存放组件:

然后在tag/index.js里面添加最基本的数据

Component({
    properties: {
        text:String
    },
    data: {},
    methods: {}
})

tag/index.wxml

<view class="container">
    <text>{{text}}</text>
</view>

tag/index.wxss

.container{
    padding:4rpx 12rpx; 
    background-color: #f5f5f5;
    color:#666666;
    border-radius: 2px; 
    display: inline-flex;
    flex-direction: row;
    align-items: center;  
    justify-content: center;
    font-size:28rpx; 
}

引入组件

首先是在主页中引入组件:

classic.json

{
  "usingComponents": {
    "v-like":"../../components/like/index",
    "v-movie": "../../components/classic/movie/movie",
    "v-tag": "../../components/tag/index"
  }
}

classic.wxml

<view class="sub-container">
    <text class="headline">短评</text>
    <view class="comment-container">
      <block wx:for="{{comments}}" wx:key="">
        <v-tag  text="{{item.content}}"></v-tag>
      </block>
    </view>
</view>

classic.js

特殊处理

此时,距离目标中的效果还是有些差距的。

首先是最新两条评论的特殊样式,这个是组件外的样式,所以不能加在组件里面,而是应该在父组件classic.wxss里面添加样式

然后,短评的每条评论后面还有点赞的数量。但是在搜索中是没有的,所以我们这里不能像前面的内容一样直接写在组件里面,而是应该做的更灵活一点:外部有值传入的时候就显示,没有传入的时候不显示也不报错。这个时候就需要使用到组件中的插槽了,关于组件的插槽,在vue部分有过简单的总结,这里就省略了,直接看使用方法:

tag/index.wxml

<view class="container">
    <text>{{text}}</text>
    <slot name="after"></slot>
</view>

和vue不同的是,在小程序中使用slot时,需要在tag/index.js中添加multipleSlots来启用插槽

然后在classic.wxml中传入值就可以了

 

posted on 2019-04-25 08:54  紅葉  阅读(326)  评论(0编辑  收藏  举报