A brief discussion on the Vuejs of mobile web development

Source: Internet
Author: User

What you're doing this time is the registration page for the Bupt People Forum app. This registration page is an embedded Web page, as it is intended to be used by both Android and iOS platforms. So it's actually doing web development on the mobile side.
There are a lot of interesting things in this process.

Demo's GitHub address is here

Content Summary:

    • META tags
    • Vuejs's Simple combat
    • CSS Mobile full-screen background
    • On the animation of CSS moving side

META tags

This is very different from the front end of the PC, and the META tag on the mobile side is a lot more. I'll just talk about the tags I use.

<!-- 1、如果支持Google Chrome Frame:GCF,则使用GCF渲染;2、如果系统安装ie8或以上版本,则使用最高版本ie渲染;3、否则,这个设定可以忽略。 --><meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"><!-- 对视窗缩放等级进行限制,使其适应移动端屏幕大小 --><meta name="viewport" content="width=device-width, initial-scale=1"><!-- 当把这个网页添加到主屏幕时的标题(仅限IOS) --><meta name="apple-mobile-web-app-title" content="北邮人论坛注册"><!-- 添加到主屏幕后全屏显示 --><meta name="apple-touch-fullscreen" content="yes" />

The second meta tag, in particular, is a very important word for mobile adaptation.

Overall layout

The overall layout is roughly a 4-5-page landscape layout. The first page is used to fill in the registration information. The following pages are used to select the layout of interest.
Registration Information page

Follow the layout page

Overall architecture

The architecture used by the front end is roughly the same:


    • Swipe to toggle page effects from Swiper.js

    • Page content is rendered using vue.js

    • Page layout and style using pure CSS, some effects using CSS3

    • The Ajax section uses Vue-resource

Back-end support frame from PHP laravel, of course, this is not the focus of this article, just mention it.

Yes, in this development, jquery has not been seen-this is the result of the development of the front-end-and slowly out of jquery's dependence. But the changes and developments that jquery brings to the front end can be replaced by no one else.

Application of Swiper.js

The introduction of Swiper.js to the page switching effect is purely because of the development of the cycle requirements are relatively short, to consider the effect and compatibility of both situations, I was lazy to find an animation library.

But the effect of this animation library is still quite satisfactory. And the overall use is quite convenient. In particular, Swiper.js can be independent of jquery.

It is also more convenient to use. I'll briefly talk about usage.

First you need to add the Swiperjs CSS file to the head tag at the top of the page:

<link rel="stylesheet" href="css/swiper.min.css')">

Then at the bottom of the page can introduce and write down the corresponding JS:

<script src="{{ asset('js/swiper.min.js') }}"></script>  <!-- Initialize Swiper --><script>  var swiper = new Swiper('.swiper-container', {    pagination: '.swiper-pagination',    paginationType: 'progress',    noSwipingClass: 'swiper-no-swiping',    allowSwipeToNext: true,    allowSwipeToPrev: true,  }); </script>

To explain, create a Swiper object, and then the container for that object is an HTML element of class called Swiper-container. The configuration for this is:

    • Pagination: '. Swiper-pagination ', show page numbers
    • Paginationtype: ' Progress ', the page number display format is the progress bar, you can see the top of the blue-white progress bar
    • Noswipingclass: ' Swiper-no-swiping ', the class name of the element that does not allow touch sliding
    • Allowswipetonext:true, allow sliding backwards
    • Allowswipetoprev:true, allow sliding forward

The corresponding HTML code can be as follows:

<!-- swiper生效的容器 --><div class="swiper-contanier">  <div class="swiper-wrapper">    <!-- 具体滑动的页面 -->    <div class="swiper-slide"></div>    <div class="swiper-slide"></div>    <div class="swiper-slide"></div>    <div class="swiper-slide"></div>  </div></div><!-- 进度条 --><div class="swiper-pagination"></div>

Some pages do not directly allow the user to swipe back and forth through the touch, but must be triggered by a click of a button. For example, the first page of the registration page, this page is required to fill out the information and then click Next to verify before you can slide to the back of the content. So as long as the page is located in the class with swiper-no-swiping this class can be implemented cannot touch the sliding switch page.

We can then use the Swiper.slidenext (Bool,time) method to manually control the movement of the page back and control the duration of the animation. This content will be said in Vue.

Vue.js's Simple combat

Since this development is only based on the original Bupt open platform project to add a fast registration function, so the introduction of Vue.js is not to restructure the entire project, but just to try to get out of jquery in the case of the development of the different experience is what to learn.

About the use of vue.js, the characteristics of what is not the focus of this article, the topic is not said. Talk about the realization of the idea. Because my vuejs is actually just an entry level, it can only be used but not to the extent that it can be mastered.

First, the entire page of bread is in a class called swiper-contanier element. Because this element includes everything you need to slide, we can actually simply think of it as a spa (single page application) that takes over the entire page with an instance of Vue (which is not responsible because the Vue is actually a modular idea).

First create a basic Vue example and bind it to Swiper-container:

var vm = new Vue({  el: ".swiper-contanier", // 将这个实例与html元素绑定起来  data: {}, // 所需要变动、关注的数据,也是vue的核心  ready: function(){}, // vue提供的钩子,用于在vue渲染视图完成后立即触发  methods: {} // 方法,用于操作、更新、改变数据而改变视图})
Registration page Implementation

As stated above, our page is built on an instance of Vue. So how do two different types of pages use one instance to take over? Here I implement the method is to use two types of data to represent each.

Let's analyze the registration page:

In fact, the middle part of the registration page is a repeating element, they are all input tags + display text tags (yes, especially note that this is not implemented with placeholder). Effect:

So the middle part can actually be seen as a list that can be rendered using Vue's v-for. The list is different only to display the text different and the input box type is different (has the text type, has the password type), so in the way of data binding we can arrange the data format of this page as follows:

data: {  main: [    {"name":"username","info":"用户名(以英文开头+英文数字)","type":"text"},    {"name":"passwd","info":"设置密码","type":"password"},    {"name":"passwd_confirm","info":"在输入一遍密码","type":"password"},    {"name":"gwno","info":"校园网账户(默认是学号)","type":"text"},    {"name":"gwpwd","info":"校园网密码(默认是身份证后六位)","type":"password"},  ],}

At the same time we create a data object that facilitates two-way binding to the front-end view UserInfo:

data: {  main: [...],  userInfo: {    username: "",    passwd: "",    passwd_confirm: "",    gwno: "",    gwpwd: ""  }}

On the front end, we can use this data to render the view:

<ul class="user-info">  <li v-for="item in main" style="position: relative;">    <!-- input输入框 -->    <!-- 此处用了v-model将数据和视图进行了双向绑定 -->    <input class="effect" type="{{item.type}}" v-model="userInfo[item.name]">    <!-- 提示信息 -->    <label>      <span>{{item.info}}</span>    </label>    <!-- input框的底下的线条 -->    <span class="focus-border cube"></span>  </li> </ul><a href="#"><button>下一步</button></a>

So a list of inputs is easy to make. Then, since it is a form, you need to verify it. And there are actually a few things to verify here:

    • is the user name legal/duplicated?
    • Did you enter the same password two times?
    • Is the password of the campus network account correct?

Only the 2nd two times the same password input can be directly judged by the front end, and the first to 3rd is the need to send the authentication request in the background by Ajax. In order to be able to manifest and discern errors, we have added an error attribute to each of the regulations under Main, and set the following three states:

    • True, indicates error with error
    • False, indicates correct, prompt correctly
    • Normal, representing default, showing default values

So we can write some methods under method to judge.

checkUserId: function(msg){  if (msg !== ""){    this.$http.post('url'+msg,function(data){      if (data.success){        this.main[0].error = false;      } else{        this.main[0].error = true;      }    })  } else{      this.main[0].error = "normal";  }},checkUserPwd: function(){    if (this.userInfo.passwd_confirm !== ""){        this.userInfo.passwd == this.userInfo.passwd_confirm && this.userInfo.passwd_confirm != "" ? this.main[2].error = false : this.main[2].error = true;    }},

Of course this is just a feature introduced, and we'll aggregate it again:

Check:function (msg,i) {var index = i; THIS.USERINFO[MSG]! = ""?  This.main[index].effect = True:this.main[index].effect = false;                                            Switch (msg) {case "username": This.checkuserid (This.userinfo[msg]);    Break Case "passwd": this.userInfo.passwd!== ""?             This.main[1].error = False:this.main[1].error = "normal";                                                             This.checkuserpwd ();                                                                         Break                                                             Case "Passwd_confirm": this.checkuserpwd ();    Break Case "Gwno": This.userInfo.gwno!== ""?           This.main[3].error = False:this.main[3].error = "normal";    Break Case "Gwpwd": This.userInfo.gwno!== ""?           This.main[4].error = False:this.main[4].error = "normal";   Break }     }

By using a check method, we can accommodate the validation of the entire form. (The validation of the campus network account is placed in the function that submits the form). In order to be able to reflect the correct, wrong and normal patterns in the view, we need to make some modifications to the front-end structure. We need to add an error message to each of the rules under Main, which is errorinfo.

So at this point the whole main structure is this:

main: [  {"name":"","info":"","type":"","error":"","errorInfo":""},  ...]

Then we need to join the Commit validation section:

submitReg: function(){  var flag = 0;  // 用于判断表单是否都是正确的  this.main.map(function(obj){    obj.error == false ? flag += 1 : flag +=0;  })  if (flag == 5){    this.$http.post('url',this.userInfo)    .then(function(res){      if (res.success){        swiper.slideNext(false,300); // 验证正确就可以进入下一页      } else{        this.main[4].error = true;      }    })  }},

Modify the View section as follows:

  <ul class= "User-info" > <li v-for= "item in main" style= "position:relative;" > <!--binding blur events--<input @blur = "Check (item.name, $index)" class= "effect" type= "{{item.type}}" V-model= " Userinfo[item.name] > <!--switch different labels based on the error type-<label> <!--Here's how to use V-show--< Span v-show= "item.error = = ' normal '" >{{item.info}}</span> <span style= "color:red;" v-show= "Item.error = = True ">{{item.errorInfo}}</span> <span v-show=" Item.error = = False ">{{item.info}}√</span> &L t;/label> <span class= "Focus-border cube" ></span> </li></ul><!--click Next to submit form information-- <a href= "#" ><button @click = "Submitreg" > Next </button></a>  

At this point, the layout and functionality of the entire registration page has been completed. But this is only a relatively simple part, we use the Vuejs of the v-for for the list rendering, using the V-model to the two-way binding data, using the method to do some data processing, using the v-show to display conditions, A basic page we have been able to experiment with so many features of Vue. And compared to the DOM operation of jquery, I think the best place for Vue here is that it's easy to submit forms. Because the two-way binding data, only need to set the data format in the background to me, I follow the back-end data structure to organize my front-end data structure and then can be directly submitted to the backend. And it saves a lot of DOM manipulation.

But in addition to the Vue part, I'd like to say two things about CSS:


    • Full Screen background

    • Input box text boost effect, and involves the processing of animation effects on the mobile side

Full Screen background
Not only is simple background-size:cover so simple, but also need to do a little processing. Let's talk about the effect I want to achieve. The effect I want is that the entire background is able to fill the entire page, and the background is fixed without scrolling with the elements as the page elements scroll up and down.

In the usual way I might write:

body,html{  height: 100%;}body{  background: url(bg.png) center 0 no-repeat;  background-size: cover;}

However, in the mobile side of the more serious consequences, that is, once the height of the page element is greater than the entire page, when scrolling the page elements, the background will also move with it. And the background will be open. It's not what I want.

Here is a little trick to use: the Before method.

body:before {  content: "";  position: fixed;  z-index: -1;  top: 0;  right: 0;  bottom: 0;  left: 0;  background: url(bg.png) center 0 no-repeat;  background-size: cover;}

This method of using before pseudo-elements is a very magical trick. You might as well try it. In this way, the background can be fixed on the mobile side and full screen is displayed.

A brief discussion on mobile animation
In the PC-side of the Web animation effect, due to the performance of the PC side is sufficient, so when writing some effects often do not take into account the performance of the problem. This time in the development of the animation has encountered the implementation of the problem. Let's take a look at the comparison of these two animations: the previous animation and one of the following animations:

The first one:
Https://codepen.io/molunerfinn/pen/zBGrxx

The second one:
Https://codepen.io/molunerfinn/pen/oLXjKz

You will find that the effects of these two things vary greatly. In fact, the final effect of the two implementations is consistent, all of which is to let the small ball in a single-lip line movement. But why does it show that the first one is so smooth and the second has a noticeable lag?

This involves a lot of things, not just repainting (repaint), but also the problem of hardware and software performance. If you are interested, you can refer to these articles:


    • Web Animation Performance Guide

    • High performance CSS3 animations

    • Performance optimization of CSS animations

The effect on the mobile side, if not optimized, is actually basically the second effect--making people seem to lag. In short, some of the effects are rendered by the browser on the mobile side-so if these effects are more complex and the performance of the mobile browser is not enough, the effect will be compared to Kaka. Some effects can be rendered by the GPU, so these effects are relatively smooth to render. And we can also artificially trigger GPU hardware rendering, through the transform of the Translate3d property can achieve hardware rendering, commonly known as hardware acceleration.

Give a simple example. If you have an element from (0,0) (100px,0), the normal idea is left:0->left:100px, and then the transition with the transition attribute. However, the effect on the mobile side is very moving, because it involves performance issues. But if we use another way: Transform:translate3d (100px,0,0), we can let this animation effect from the GPU to render, then the effect on the mobile side is completely acceptable smooth.

In fact, the actions that trigger GPU rendering are opacity,transform,transition,animation and so on. However, changes in properties like top,left,color,size do not trigger GPU rendering.

The example described in this article is that when the focus is focused on the input box, the text moves up and has a color change. What was meant to be achieved was the size of the text and the change. However, due to the above mentioned situation, when it comes to size changes, the effect will be greatly discounted. I can only cut off this effect. The implementation of the text up is actually using the transform of the Translate3d way, moving it upward, and with the transition to do a bit of transition.

The specific CSS implementations are roughly as follows:

input:focus ~ label,.trans {                                                                   color: #fff;                                                                                   transition: 0.3s;                                                                              -webkit-transform: translate3d(0, -20px, 0);                                                   -moz-transform: translate3d(0, -20px, 0);                                                      -ms-transform: translate3d(0, -20px, 0);                                                       transform: translate3d(0, -20px, 0);                                                         }

It's not hard actually, is it?

Focus on the implementation of the layout page

In fact, from the implementation of the registration page has been able to look at the way the layout page implementation. Actually focus on the layout page, but also the rendering of the list, in the data to define the corresponding attributes are OK. Then use a picked property to see if it is selected. When you finally complete the registration, assemble all the selected lists into the appropriate array and submit them to the background. Because these methods have been mentioned in the registration page, we will not repeat them.
Summarize
Simply summarize what you learned in the development of this mobile terminal.


    • Simple use of vuejs, data binding from DOM operations

    • Implementation of full screen background

    • The realization of smooth animation effect

In fact, there are a lot of things to talk about in terms of compatibility, but the limitations of space and the main content of this article are not related to the compatibility of the mobile end, so it is not documented in terms of compatibility.

I still haven't used the more popular flex in typography, and I haven't used the idea of component development for Vue. These are the parts that need to be improved. However, the development process through the art of guidance, I wrote the page before the attention of many details, such as line size, element spacing, color collocation and other things to point out, these things are not simple to achieve. In short, if there is time, I think I can integrate the design knowledge into my front-end development, presumably can make my work more in line with the aesthetic and user experience it ~

Demo's GitHub address is here

Article Author: molunerfinn
Article Link: https://molunerfinn.com/vuejs-1/
Copyright Notice: All articles in this blog are subject to the CC BY-NC-SA 4.0 license Agreement except for special statements. Reprint please specify from markszのblog!

A brief discussion on the Vuejs of mobile web development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.