碧血红天的HomePage

微信小程序 — 制作一个用户信息组件

这里我们来学习制作一个用户信息的名字展示组件,上面会展示用户的头像,用户的名字,和用户的等级等等。一般的需要用户登录的小程序都会存在一个这样的界面,就像如下图:

这里我们需要了解几个如下的知识点:

  • 如何设置背景色
  • 如何让元素左右和上下布局
  • 如何显示一个图片
  • 如何设置文字的大小和颜色
  • 如何设置元素之间的空隙
  • 如何设置一个视图的大小

设置视图的大小

设置一个大小,也就是设置我们看见的这个View的宽度和高度。此View的宽是100%拉满,高度则为一个固定值。我们是使用CSS样式表来写这样的效果,样式表的定义是写在wxss文件中,首先,我们在components文件夹下创建一个组件,使用在开发者工具选中文件夹右键创建组件的方式创建,这样会自动生成所需要的四个文件。现在我们在wxss中定义样式表:

.account-container{
  display: flex;
  align-items: center;
  height: 260rpx;
  background-color: rgb(240, 119, 6);
}

我们把整个view的这个区域称为一个container,样式表的名字无所谓,但是前面的那个点“.”是又讲究的,还有其它的模式。它的作用是个选择器的作用,也就是让那些元素能够生效从样式内容,点代表所有使用了此样式的元素都生效。

display:里面的display代表当前的元素是使用flex布局,我的理解就是此布局可以横向排列或则竖向排列元素。微信也建议使用此布局就可以了,一般大部分情况使用此布局都能满足。

align-items:display布局的话,下面的元素都是默认从左上角依次排列元素,align-items告诉下面的元素是用上下居中的方式排列。也就是我们看见下面的元素是垂直居中排列的关键。

height:定义元素的高度,px是个单位描述,代表像素高度。rpx是微信小程序扩展的一个单位,也相当于一个比例。

background-color:设置背景颜色的说明,我这里设置成橘黄色,颜色的表示用多种,比如这里的rgb方法,还能#ff00ff这样的方式表示一个颜色。

然后我们在wxml来定义书写我们的界面元素,通过使用先定义的样式来设置元素的表现样式:

<view class="account-container">
<view>

我们在需要使用的的元素里面使用一个class元素来赋值使用的元素样式,样式的名字是不用带上选择器说明的那个点。现在表现得效果如下:

橘黄色得高度就是我们定义的260rpx高度的一个元素,view意思就是一个可见的视图元素,如果下面要装什么需要看见的元素就用此元素就可以。

设置头像图片

现在我们需要设置一个圆形的头像图片,然后距离左边边框一定距离,居中在视图显示。

.account-avatar {
  overflow: hidden;
  width: 128rpx;
  height: 128rpx;
  margin-left: 30rpx;

  border-radius: 50%;
  display: flex;
}

我们又在wxss中定义样式表,width 和 height就是头像图标的高度和宽度。

overflow:这个是告诉使用此样式的元素,里面的内容超过了宽度和高度是怎么表现。它有4种处理方式:

  • visible:默认方式,就是内容不裁剪,下面的内容会直接超过外面的元素的大小。
  • hidden:内容会被裁剪,大小就是外面元素框的大小进行裁剪下面的内容元素。
  • scroll:内容会被裁剪,可以添加一个滚动条来看被裁剪了的内容。做滚动区域就非常有用。
  • auto:直接适用到滚动区域的大小,如果内容超过了滚动区域的大小就会自动添加上滚动条。

这里我们设置为hidden,当图片资源超过现在顶一个128rpx就执行裁剪。

margin-left:表示距离左边30rpx的距离。

border-radius:表示边框的圆角,这里是50%,也就是会变成一个圆形。

然后在wxml种添加一个视图来使用此样式表:

<view class="account-container">
  <view wx:if="{{canIUseOpenData}}">
    <view class="account-avatar" bindtap="bindViewTap">
      <open-data type="userAvatarUrl"></open-data>
    </view>
  </view>
</view>

wx:if先不用管,这里就是一个程序动态控制头像的显示内容的,这句话的意思就是,如过canIUseOpenData是true,那么就有下面这些view,否正就没有下面那些view,这也就是动态控制视图表现得手段。

我们在第三个view看见使用了我们定义得account-avator,bindtap得作用是指明当点击这个视图得时候,会调用js文件种定义的一个叫bindViewTap的方法。open-data是一个特殊的元素,会使用微信小程序预设值的一些内容,它里面的type标注的就是具体是哪个内容,这里是用户头像的url。

设置用户名字

可以看最上面,名字下面还存在一个内容,也就是上下表现得布局。现在得内容就可以想成是一个左右布局中有2个元素,一个头像,一个名字信息,然后名字信息的视图又是上下布局,他们的布局简单结构如下:

每一个颜色的框就代表一个view元素。现在我们要为名字定义一个上下结构的容器:

.account-name-container {
  display: flex;
  flex-direction: column;
  margin-left: 15px;
}

display:此容器依然使用flex方式布局,

flex-direction:告诉这个flex布局的方向,默认是水平,也就是从左到右。column列方式,也就是上下布局。

margin-left:距离左边的头像15个像素。

然后我们定义名字的视图样式:

.account-name {
  color: white;
  margin-top: -16%;
}

color:代表下面文字的颜色。

margin-top:文字需要向上便宜一些,否正文字会在正中间。

在定义下面显示vip信息的视图样式:

.vip-bg {
  overflow: hidden;
  width: 104px;
  height: 23px;
  align-items: center;
  border-radius: 5px;
  background-color: #fce3ce;
  margin-top: 10px;
  display: flex;
}

我们是用到圆角,为了裁剪掉圆角外的部分使用了overflow:hidden。

下面定义vip的文字样式:

.vip-name {
  color:#ae816e;
  font-size: 14px;
  margin-left: 5px;
}

font-size:是文字的大小。

color:是文字的颜色。开始学习总会错误的理解这个字段,认为这个是背景色。

然后定义一个icon的大小:

.icon {
  display: inline-block;
  width: 22px;
  height: 22px;
}

display:inline-block代表一行内块状显示元素。毕竟上面我们父容器样式是竖向显示,所以我们再限定为一行内显示,就不换行了。

定义一个名字上修改的图标样式:

.name_edit_icon {
  background-image: url("data:image/svg+xml;base64,PHN2ZyB0PSIxNjE4MzY3MjE2NzMwIiBjbGFzcz0iaWNvbiIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHAtaWQ9IjY1NTMiIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiI+PHBhdGggZD0iTTY5NC4wMzczMzMgMjEzLjMzMzMzM3Y2NEgyMzQuNjY2NjY3djQ2OS4zMzMzMzRoNTEyVjUxMmg2NHYyMzQuNjY2NjY3YTY0IDY0IDAgMCAxLTY0IDY0SDIzNC42NjY2NjdhNjQgNjQgMCAwIDEtNjQtNjRWMjc3LjMzMzMzM2E2NCA2NCAwIDAgMSA2NC02NGg0NTkuMzcwNjY2eiBtMTM2Ljc0NjY2NyAyNC4yMzQ2NjdsNDUuMDk4NjY3IDQ1LjM5NzMzMy0zNDMuNzIyNjY3IDM0MS4yOTA2NjcgMC4xMjggMC4xMjgtNDYuNTkyIDEuNTc4NjY3IDEuMzIyNjY3LTQ3LjI3NDY2NyAwLjA4NTMzMyAwLjEwNjY2NyAzNDMuNjgtMzQxLjIyNjY2N3oiIHAtaWQ9IjY1NTQiIGZpbGw9IiNmNGY0ZjQiPjwvcGF0aD48L3N2Zz4=");
  background-size: cover;
}

background-image:定义图片资源的路径,这里使用的是BVG转的base64的图片资源方式,有些复杂,后面单独介绍。

background-size:图片的大小,此处使用覆盖。没有这句话,图片会试原始的大小平铺,导致就不正常。

然后再wxml种组装起视图结构,再使用上我们定义的样式:

<view class="account-container">
  <view wx:if="{{true}}">
    <view class="account-avatar" bindtap="bindViewTap">
      <open-data type="userAvatarUrl"></open-data>
    </view>
  </view>
  <view class="account-name-container">
    <view class="account-name">
      <open-data type="userNickName"></open-data>
      <text class="name_edit_icon icon" bindtap="bindEditName"></text>
    </view>
    <view class="vip-bg">
      <image src="/res/vip.png" style="width:20px;height:20px;margin-left:5px;" mode="aspectFit"></image>
      <text class="vip-name">普通会员</text>
    </view>
  </view>
</view>

我们可以看见name_edit_icon 为什么后面还跟了一个 icon 。这个意思是直接使用了2个css样式的效果。

vip那个图标我们直接使用的是本地资源,style属性也是设置css样式内容,只不过是直接在这个下面写css的具体内容,而不是css的名字了。

image元素节点下的mode是设置图片节点的适配方式,aspectFit直接宽高按比列适应当前元素设置的宽度和高度。

通过上面的内容,就实现了一个基本上静态的页面,头像和名字目前使用的是开发数据动态设置的。动态设置的数据需要在js文件种书写逻辑。

动态逻辑

前面的部分是一个静态页面的样式,最后,但是里面的头像和名字需要真实的读取微信账号的数据才。所以这部分的内容就是动态逻辑部分了。动态逻辑这些内容需要我们书写在JS文件中。

属性定义

有时候,我们需要定义一些属性,属性需要定义在js文件中的properties中

  properties: {
    innerText: {
      type: String,
      value: 'default value',
    }
  },

就如上面的书写过程,然后我们能在wxml文件中使用2个大括号来使用这个属性变量:

<text>{{innerText}}</text>

组件中还可以定义初始化的数据,放在data下面:

  /**
   * 组件的初始数据
   */
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && 
    wx.canIUse('open-data.type.userNickName') 
  },

同理,定义的数据依然可以通过2个大括号在wxml中引用:

<text>{{canIUseOpenData}}</text>

上面逻辑中我们用到一个wx.canIUse的方法,这是微信小程序提供的内部API。可以测试是否提供的属性和方法可用。

在组件中,如果我们需要添加响应view的bindtap响应的方法,我们需要定义方法在methods之中:

methods: {
    bindEditName(){
      console.log("Edit NickName")
    },
}

这里一个完整的js代码,我已经去掉了许多现在不必要的内容:

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    innerText: {
      type: String,
      value: 'default value',
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && 
    wx.canIUse('open-data.type.userNickName') 
  },

  /**
   * 组件的方法列表
   */
  methods: {
    bindEditName(){
      console.log("Edit NickName")
    },
  },
})

161 评论

  1. I like it when folks get together and share ideas. Great site, stick with it!

  2. I was just seeking this information for some time. After six hours of continuous Googleing, finally I got it in your site. I wonder what’s the lack of Google strategy that don’t rank this kind of informative web sites in top of the list. Usually the top web sites are full of garbage.

  3. Pretty! This has been an extremely wonderful post. Thanks for providing this information.

  4. You made some nice points there. I looked on the internet for the subject matter and found most individuals will consent with your blog.

  5. A motivating discussion is worth comment. I do believe that you should write more on this subject, it may not be a taboo subject but generally folks don’t speak about these topics. To the next! Best wishes!!

  6. Presenting symptom of malignancy Depression may be a presenting symptom of some primary malignancies, most notably pancreatic carcinoma stromectol for humans for sale

  7. An outstanding share! I’ve just forwarded this onto a friend who had been conducting a little homework on this. And he actually ordered me lunch due to the fact that I found it for him… lol. So let me reword this…. Thanks for the meal!! But yeah, thanks for spending time to talk about this issue here on your web site.

  8. propecia no script If you do violate any rule law, you will be going against the company s policies and it will have no legal obligation to defend your actions or fund your self defense

  9. May I simply just say what a relief to uncover an individual who truly knows what they’re discussing online. You actually know how to bring an issue to light and make it important. A lot more people need to look at this and understand this side of your story. I can’t believe you aren’t more popular because you definitely possess the gift.

  10. I like reading a post that will make men and women think. Also, many thanks for allowing for me to comment!

  11. My doctor then told me I should try an egg donor clomid for women

  12. Can I just say what a comfort to find somebody who genuinely knows what they’re talking about online. You certainly know how to bring an issue to light and make it important. More and more people ought to check this out and understand this side of your story. I can’t believe you are not more popular because you surely possess the gift.

  13. I was able to find good advice from your articles.

  14. priligy fda approval A few patients have developed a rash or breast tenderness while taking LONITEN Tablets, but this is unusual

  15. Good info. Lucky me I reach on your website by accident, I bookmarked it.

  16. This is a topic which is near to my heart… Take care! Exactly where are your contact details though?

  17. Spot on with this write-up, I really believe this amazing site needs a great deal more attention. Iíll probably be returning to see more, thanks for the info!

  18. Very good information. Lucky me I ran across your site by chance (stumbleupon). I’ve saved as a favorite for later!

  19. There is definately a great deal to know about this subject. I love all the points you’ve made.

  20. cialis buy online We thank Seren Г–zer for contributing to study identification and data extraction

  21. When I originally commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove me from that service? Thanks!

  22. Hi, I do believe this is an excellent blog. I stumbledupon it 😉 I will come back once again since I book-marked it. Money and freedom is the greatest way to change, may you be rich and continue to guide other people.

  23. Excellent web site you have here.. Itís difficult to find quality writing like yours these days. I seriously appreciate individuals like you! Take care!!

  24. We’re a group of volunteers and starting a brand new scheme in our community. Your website offered us with useful info to work on. You have performed an impressive process and our entire group will probably be thankful to you.

  25. Yay google is my world beater helped me to find this great website ! .

  26. I’m extremely impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you customize it yourself? Either way keep up the nice quality writing, it’s rare to see a great blog like this one today..

  27. I have recently started a web site, the information you provide on this site has helped me greatly. Thanks for all of your time & work.

  28. You actually make it appear so easy together with your presentation but I find this topic to be really something that I believe I might never understand. It seems too complicated and very extensive for me. I am looking forward on your subsequent publish, I¦ll try to get the cling of it!

  29. I would like to thnkx for the efforts you have put in writing this blog. I am hoping the same high-grade blog post from you in the upcoming as well. In fact your creative writing abilities has inspired me to get my own blog now. Really the blogging is spreading its wings quickly. Your write up is a good example of it.

  30. I appreciate, cause I found just what I was looking for. You’ve ended my four day long hunt! God Bless you man. Have a nice day. Bye

  31. I will immediately grab your rss as I can’t find your email subscription link or newsletter service. Do you have any? Kindly let me know so that I could subscribe. Thanks.

  32. Attractive section of content. I simply stumbled upon your weblog and in accession capital to say that I acquire actually enjoyed account your blog posts. Any way I’ll be subscribing in your augment and even I success you get right of entry to consistently rapidly.

  33. I like forgathering useful information , this post has got me even more info! .

  34. Wow! This can be one particular of the most useful blogs We have ever arrive across on this subject. Basically Wonderful. I’m also a specialist in this topic so I can understand your effort.

  35. This web site is my inhalation, very good design and perfect subject matter.

  36. Hey There. I found your blog using msn. This is a very well written article. I will be sure to bookmark it and return to read more of your useful information. Thanks for the post. I’ll certainly return.

  37. Way cool, some valid points! I appreciate you making this article available, the rest of the site is also high quality. Have a fun.

  38. What¦s Taking place i’m new to this, I stumbled upon this I’ve discovered It positively helpful and it has aided me out loads. I am hoping to contribute & aid different users like its helped me. Good job.

  39. Spot on with this write-up, I actually suppose this website wants way more consideration. I’ll in all probability be again to learn much more, thanks for that info.

  40. certainly like your website but you have to take a look at the spelling on several of your posts. Many of them are rife with spelling issues and I in finding it very troublesome to inform the truth nevertheless I will definitely come again again.

  41. Hello there! Do you use Twitter? I’d like to follow you if that would be okay. I’m undoubtedly enjoying your blog and look forward to new posts.

  42. Greetings! Very helpful advice on this article! It is the little changes that make the biggest changes. Thanks a lot for sharing!

  43. Become a master in everything with this!

  44. Its the brand-new innovation that will alter your life.

  45. Amazing is an all-in-one life management tool that will make you much more productive as well as tension free.

  46. I’m very happy to read this. This is the type of manual that needs to be given and not the random misinformation that is at the other blogs. Appreciate your sharing this best doc.

  47. Terrific to get the most out of your money. Amazing!

  48. It will certainly assist you obtain whatever done in a portion of the time.

  49. Discover how else this can help you with your health and wellness goals!

  50. You made some clear points there. I did a search on the topic and found most persons will approve with your site.

  51. Do you understand about the Amazingness lifestyle?

  52. This is a time saving life changer!

  53. The Phenomenal will certainly aid you plan your days, weeks and months easily to ensure you’re obtaining one of the most out of life!

  54. Hello, you used to write great, but the last few posts have been kinda boringK I miss your super writings. Past several posts are just a bit out of track! come on!

  55. The Amazingness life management device will certainly assist you take your performance to the following degree!

  56. The very best and most prominent of all the items.

  57. This item is the most effective of a standard.

  58. The most outstanding service for getting points finished. This is exactly what your life needs.

  59. Remarkable is the best name for this item.

  60. Pg slot gamingเกมสล็อตสมาชิกใหม่ยอดนิยมอีกทั้งในรวมทั้งเมืองนอกเป็นเกมเสี่ยงดวงอีกแบบหนึ่ง ที่ได้กำลังเป็นที่นิยมไปทั้งโลก ขอแนะนำค่าย pg slot เป็นค่ายที่มีภาพสวยเกมสนุก

  61. slot wallet slotwallet เป็นเกมสล็อต ( pg slot )slot ที่มาแรง สร้างความระทึกใจให้กับผู้เล่นได้อย่างสม่ำเสมอ ด้วยการอัปเดตเกมใหม่ๆออกมาอยู่เรื่อยรวมมากยิ่งกว่า 200 เกม 2022

  62. This is an outstanding device to help you with everything else.

  63. You are worthy of the most effective of whatever in life. And also this product can assist you get there!

  64. This guide will assist you to take your organization as well as individual abilities to the next degree!

  65. best online poker for us players play poker texas holdem free aol online is online poker legal in ma

  66. I like this site very much so much excellent info .

  67. online gambling united states top online gambling sites florida online gambling

  68. Can I show my graceful appreciation and give my hidden information on really good stuff and if you want to with no joke truthfully see Let me tell you a brief about howto make money I
    am always here for yall you know that right?

  69. website this is very good, I like, material that is too awesome and, unique, continue to work if you believe eat certainly can, me comet with hope can help you ask for permission okay totosoju

  70. Being remarkable is less complicated than you believe!

  71. Incredible is the one quit solution for a much more healthy and balanced as well as productive life.

  72. web this is very good, I like, material that is too awesome and, unique, continue to work unless you believe eat certainly can, me comet together hope able support you ask for permission okay totosoju

  73. website this is very good, I like, material that is absolutely fantastic and, unique, continue to work if you believe eat certainly can, me comet with hope can support you ask for permission okay totosoju

  74. web this is very good, I like, material that is absolutely awesome and, unique, continue to work unless you sure eat certainly can, me comet together hope can support you ask for permission okay totopanen

  75. Incredible is a proprietary formula for aiding you complete a lot more and really feel better regarding your life.

  76. All from one little pill, Phenomenal gives you awesome energy!

  77. Amazingness can aid you change your life right in methods you never believed possible.

  78. site this is too good, I like, material that is absolutely fantastic and, unique, continue to work except you sure eat certainly can, me comet with hope can help you ask for permission okay totopanen

  79. In the Dutch health care system, the general practitioner plays a pivotal role and acts as a gatekeeper of medical care and information priligy buy PMID 26892682 Free PMC article

  80. service delivery essay starting a business essay essay on commitment to public service

  81. The usual smiles on the faces of many small and medium sized officials were also gone clomid next day delivery Alwin Huitema Jos H

  82. amiodarone will increase the level or effect of warfarin by affecting hepatic enzyme CYP2C9 10 metabolism safe place to buy zithromax

  83. legit cialis online Rarely, if ever, in written exchanges

  84. The results with monoclonal antibody 2G7 in this Example suggest that the humanized antibodies herein would be useful for treatment of malignant melanoma nolvadex side effects male Neuromuscular Blocking Agents Tetracyclines may enhance the neuromuscular blocking effect of Neuromuscular Blocking Agents

  85. Kenton QExKTvEcgIXhaEt 5 20 2022 cialis coupon

  86. Sensational is the efficiency application that will certainly change your life.

  87. Discover the keys to a best life as well as just how to make it occur.

  88. Ofirok couldn t new blood pressure chart help but feel a little strange, Marshal Rocherio s weaning off blood pressure medicine attitude of not caring about himself seems to be just a person watching the fun Priligy Normally functioning adrenals are supposed to put out the most cortisol in the morning, and the levels of cortisol should decline during the day, until very little cortisol is secreted at bedtime

  89. Presenting the Amazingness life hack. This one easy adjustment will certainly make your days more joyous as well as effective .

  90. Direct correspondence or inquiries to clomid stockist uk Their doubling time exceeds 100 h, while doubling rate for MCF 7 cells is about 29 and T47D about 32 h

  91. Extraordinary is an all-in-one time administration toolkit that can assist you get even more done in much less time.

发表评论