Sharing of learning notes in uni

Table of contents

  • 01. Summary of problems encountered
  • 02. About layout settings
  • 03. Basic grammar summary
  • 04. About interaction
  • 06. About returning data
  • 07. About network requests
  • 08. About page refresh
  • 09. Notes
  • 10. To be solved and considered

01. Summary of problems encountered

  • In my page, there is a problem defining the class of view as line when setting the divider line for the item, but you can change the name to cell line. It is assumed that there is a conflict with line when setting the class name.
  • Jump from page A to page B, close B to return to A, how to return data? Looking at the upward scheme, we found that there were problems, and finally replaced them with access values.
  • For example, when switching the page layout view to refresh, my page is logged in, not logged in, and the member uses v-if instead of v-show to refresh the page.
  • For network request, in the student information page, use post to submit data. You need to set the header request header, otherwise the request exception will appear
  • Data binding, such as changing the background color of view dynamically, it is recommended to use class setting instead of style setting
  • Assign a value to a field in data. It is recommended to assign the value as a '' string, even if it is an integer. For example, use sex: "3" instead of sex: 3
  • When the parent, child and other multi-level controls have click events, in order to avoid bubble event conflicts, you can add@ tap.stop Prevent bubbling events
  • Sometimes the relative path setting does not work when the image is introduced. Why? According to Kejia's specification documents, it is recommended to use absolute path for url introduction rules
  • In the provincial and urban area control, even if the height is set for the parent view of the scroll view, you still need to set the height for the scroll view, otherwise the page will be full

02. About layout settings

  • Introduction to flex layout properties
    • This is to write layout and query at the same time
    display: flex; //Display objects as flex boxes
    display: inline-flex; //Show objects as inline block level flex boxes parent elements are adaptive by default based on child element width and height
    
    //Spindle direction
    flex-direction: row; //Items are arranged horizontally, starting from the left end
    flex-direction: column; //The main axis is vertical and the starting point is at the right end
    
    //How to wrap
    flex-wrap: nowrap; //Items don't wrap
    flex-wrap: wrap; //Wrap, first line above
    flex-wrap: reverse; //Wrap, first line below
    
    //Spindle alignment
    justify-content: flex-start //Align left
    justify-content: flex-end //Align right
    justify-content: center //Center
    justify-content: space-between //Align at both ends, equally spaced between items
    justify-content: space-around //Equally spaced on both sides of each item
    
    //Alignment of items on cross axis
    align-items: center; //Center vertically
    align-items: flex-start; //Cross axis start alignment
    align-items: flex-end; //Cross axis end alignment
    
    //Alignment of multiple axes
    align-content: center; //Center vertically
    align-content: flex-start; //Cross axis start alignment
    align-content: flex-end; //Cross axis end alignment
    
  • Common styles
    position:sticky //Sticky positioning (positioning is based on the user's scrolling position, and specific thresholds need to be specified when using, such as top:0)
    position:static //Default positioning (no positioning)
    position:fixed //Fixed positioning (fixed in the window position, the window scrolling will not move)
    position:relative top:10px //Relative positioning (relative to its normal position)
    position:absolute //Absolute positioning (relative to the nearest positioned parent, or < HTML > if there is no positioned parent)
    
    border-radius:30upx; //Fillet radius
    text-indent:20px //text-indent
    letter-spacing:1px //Word spacing
    vertical-align: middle; //Picture vertical center
    z-index //Stacking order of overlapping elements
    
    //https://www.cnblogs.com/skura23/p/6505352.html
    :active,The element changes color when clicked, but the color disappears when clicked
    :focus, The element changes color after being clicked, and the color does not disappear after clicking
    
  • font in css does not support shorthand
    //error
    font: bold 28rpx;
    
    //correct
    font-size:28rpx;
    font-weight:bold;
    
  • Scroll view needs to set height
    • In the provincial and urban area control, set the height of 500rpx for the parent view. If you do not set the height for the regional scroll view, the regional content will be full of the control, which will lead to the page jitter of switching provincial and urban areas.
    • The solution is to set the height for the child scroll view.

03. Basic grammar summary

  • v-if and v-show
    • For example, in my page, there are login status, member status and not login status, and the layout can be hidden and displayed dynamically. v-if is used at this time
    • The difference between v-if and v-show: whether the former will be removed in dom, and the latter display:none
    • v-if is recommended for refreshing the switch view, such as login / login.
    • If the use scenario needs to switch very frequently, it is better to use v-show; if the conditions rarely change at runtime, it is better to use v-if. Read more about this article
  • About data binding
    • For example, the user center selects gender, selects switching color, and needs to pay attention to writing specifications. The code is as follows:
    //Correct writing
    <text class="cell-sex" :class="{'cell-sex-select': isSelcetMan}" @click="clickMan">male</text>
    <text class="cell-sex" :class="{'cell-sex-select': !isSelcetMan}" @click="clickWoman">female</text>
    
    
    //Wrong writing
    <text :style="{color:isSelcetMan?'#F88B32':'#666666 '} "class =" cell sex "@ Click =" clickman "> male < / text >
    <text :style="{color:!isSelcetMan?'#F88B32':'#666666 '} "class =" cell sex "@ Click =" clickwoman "> female < / text >
    
  • Note on assignment in data
    • On the student information page, when setting sex as integer in data, it is found that the submitted student information report 500 is abnormal, but if the assignment is changed to "3", it can be found. Is it true that even if the binding is a number, the web page and the mobile terminal will only get a string
    export default {
    	data() {
    		return {
    			//Gender, 1 male, 2 female
    			sex : "3",
    			// sex : 3,
    		};
    	},
    }
    
    //Submit student information, the sex parameter is integer
    	async updateUserInfo(name,sex,birthday,grade,school_id,entrance_year) {
    		const data = {
    			sex : sex,
    		};
    		let header = {
    			'content-type': 'application/x-www-form-urlencoded'
    		};
    		const result = await this.$zwwl.api.updateUserInfo(data,header);
    		//Network request successful
    		if(result.data!=null && result.code == 200){
    		}
    	},
    
  • About@ tap.stop.prevent
    • For example, select the city list control, province, city, district three-level tab. Click the province list item, request the city data of the province, and then switch to the city tab page. At the same time, when the selection is complete, click the control to close the city list pop-up window
    • What is called event bubble: when you click the outside, the event of the inside element will not be triggered; but when you click the inside element, the event of the outside element will be triggered, which is event bubble!! See this blog for details
    • To prevent the event from bubbling, add a layer of label on the outer layer < view@ tap.stop= "Onarea itemclick (ind)" > < / View >, adding. Stop directly to the method to be used is invalid
    <view v-if="tabTitle.length > 0 && show" :class="[{'tabBlock__animation' :show},'tabBlock']" @tap.stop.prevent="onClickModule">
    	<!-- Provincial and urban areas, and confirm button -->
    	<scroll-view scroll-x="true" scroll-with-animation :scroll-left="tabsScrollLeft" @scroll="scroll">
    		<view :class="'tab'" id="tab_list" >
    			<view v-for="(item, index) in tabTitle" :key="index" :class="['tab__item',{'tab__item--active':currentIndex === index}]" :style="{color: (currentIndex === index ? `${itemColor}`: '')}" id="tab_item" @tap.stop.prevent="onSelect(index)">
    				<view class="tab__item-title">
    					 {{item.title}}
    				</view>
    			</view>
    			<view class="confirm" @tap.stop.prevent="onConfirm">
    				//determine
    			</view>
    			<view class="tab__line" :style="{ background: lineColor, width: lineStyle.width, transform: lineStyle.transform,transitionDuration: lineStyle.transitionDuration}"></view>
    		</view>
    	</scroll-view>
    
    	<!-- Regional data -->
    	<scroll-view class="content-view" scroll-y="true">
    		<view class="item-view" v-for="(item,ind) in areaListData" :key="ind" @tap.stop.prevent="onAreaItemClick(ind)">
    			<view class="desc">{{item.name}}</view>
    			<view class="cell-line"></view>
    		</view>
    	</scroll-view>
    </view>
    
  • this scope problem
    • First solution
      • The solution is to assign this to another variable outside the closure
      //It can be found that this operation can solve the scope problem
      changeTitle3(){
      	//assignment
      	var me = this;
      	uni.setStorage({
      	    key: 'storage_key',
      	    data: 'hello',
      	    success: function () {
      			me.title = "Change title 3";
      	        console.log('changeTitle2------success');
      	    }
      	});
      },
      
    • Second solution
      • You can also solve this problem by using the arrow function. Think about why? But this is not recommended
      changeTitle4(){
      	uni.setStorage({
      	    key: 'storage_key',
      	    data: 'hello',
      	    success:() => {
      			this.title = "Change title 4";
      	        console.log('changeTitle2------success');
      	    }
      	});
      },
      

04. About interaction

  • In the list of provincial and urban cities
    • There is a problem
      • When switching between different provinces and changing the order of getting City array, the index index received by clicking the event will not be updated, or the index value before the array order changes.
    • Solution
      • When the page needs to have two or more v-for at the same time, the key value needs to be set correctly according to your final application environment. If it is suitable for multi-end platform, the following methods can be used as reference:
      • 1. Make some parts that need v-for into components, so that there is no more than one v-for on the page
      • 2. Use a field value of the traversal element as the key, but the field value must be unique and not repeated, as follows: list.id wait
    • Why key is needed
      • Refer to: Demonstrate why v-for adds key
      • There are differences between v-for loop integers and other platforms. For example, in v-for="(item, index) in array", the H5 platform item starts from 1, and other platform items start from 0. The second parameter index can be used to keep consistent.
      <!-- Provincial and urban areas, and confirm button -->
      <scroll-view scroll-x="true" scroll-with-animation :scroll-left="tabsScrollLeft" @scroll="scroll">
      	<view :class="'tab'" id="tab_list" >
      		<view v-for="(item, index) in tabTitle" :key="index" :class="['tab__item',{'tab__item--active':currentIndex === index}]" :style="{color: (currentIndex === index ? `${itemColor}`: '')}" id="tab_item" @tap.stop.prevent="onSelect(index)">
      			<view class="item-title">{{item.title}}</view>
      		</view>
      	</view>
      </scroll-view>
      
      <!-- Regional data -->
      <scroll-view class="content-view" scroll-y="true">
      	<view class="item-view" v-for="(item,ind) in areaListData" :key="ind" @tap.stop.prevent="onAreaItemClick(ind)">
      		<view class="desc">{{item.name}}</view>
      		<view class="cell-line"></view>
      	</view>
      </scroll-view>
      

06. About returning data

  • How to close the current page and return to the previous page
    • Page return call uni.navigateBack , users press the back button in the upper left corner, Android users click the physical back button
  • The first type of returned data
    • Use uni.$emit() and uni.$on(). $emit is the trigger event, $on is the accept event, matched by eventName. This method is similar to eventBus event notification in Android
      • uni.$emit(eventName,OBJECT)
      uni.$emit('update',{msg:'Page update'})
      
      • uni.$on(eventName,callback)
      uni.$on('update',function(data){ 
          console.log('Listening for events from update ,Carry parameters msg Is:'  + data.msg);  
      })
      
    • There is a problem: you need to contact to listen. Listening events will be executed multiple times
  • The second type of returned data
    • Operate on page b
    var pages = getCurrentPages();
    //Previous page
    var prevPage = pages[pages.length - 2]; 
    prevPage.setData({
    	sx1:"Parameter 1",
    	sx2:"Parameter 2",
    })
    uni.navigateBack({
    	delta:1
    });
    
    • Operate on page a
    onShow(object){
    	if(!!object){
    		console.log('vue onShow' + object)
    	}
    },
    
    • Error reporting: "message":“ prevPage.setData is not a function"
  • The third type of returned data
    • Operate on page b
    var pages = getCurrentPages();
    //Previous page
    var prevPage = pages[pages.length - 2]; 
    var object={
    	sx1:"Parameter 1",
    	sx2:"Parameter 2",
    }
    //Focus $vm
    prevPage.$vm.otherFun(object);
    uni.navigateBack();
    
    • Operate on page a
    //This method is written in phones
    otherFun(object){
    	if(!!object){
    		console.log(object)
    	}
    }
    
    • Error message: "message": "prevpage$ vm.otherFun is not a function",
  • How to return data at present
    • We haven't found a good solution yet. Ask colleagues to save the data, close the page, and then get it in onShow method

07. About network requests

  • Network request refers to the pit of POST
    • In student center, users need to submit data request interface after filling in data. When using post request, please note that the request header must be added, otherwise the data cannot be uploaded
    • Why does this error occur
      • When network requests are made by POST, normal network requests cannot be made without adding header headers. At this time, the default request method content type type is application/json
    • Solution
      let header = {
      	'content-type': 'application/x-www-form-urlencoded'
      };
      const result = await this.$zwwl.api.updateUserInfo(data,header);
      
    • Reference article: Uni app network request refers to the pit of POST
  • If you do not add a header header
    • You can view directly without adding header header. The default content type is: application/json;charset=UTF-8
    • Add header header, set to 'content type': 'application / x-www-form-urlencoded'
  • These two differences
    • application/x-www-form-urlencoded indicates the form, and the format of upload parameter is key = value & key = value
    • application/json represents that parameters are passed to the background as json strings

08. About page refresh

  • For example, in the landing page, there are view s of not logged in, logged in, member and other statuses. After the user performs an action and changes some statuses, he needs to refresh the page to re render the page.
  • The first is to use the original method: location.reload(); however, if the page is forced to refresh, there will be a short flash, and the user experience effect is not good.
  • The second is to use the route jump provided by vue: this$ router.go (0); as with the first, force refresh.
  • The third way is to use v-if. The specific operations are as follows. You only need to change the property value of isShow to refresh
    <template>
    	<view>
    		<!-- v-if v-show The difference: whether the former will be in dom Is removed, the latter display:none -->
    		<view v-show="isShow">
    			now you see me haha
    		</view>
    	</view>
    </template>
    
    <script>
    	export default {
    		data() {
    			return {
    				isShow: true,
    			};
    		}
    	}
    </script>
    
    <style>
    
    </style>
    

09. Notes

  • The absolute path should be used to introduce pictures into the component. Using this / static /... Is the best
  • The main page life cycle uses onLoad instead of created, and onReady instead of mounted. Use the original created and mounted in the component
  • To prevent the event from bubbling, add a layer of label on the outer layer < view@ tap.stop= "Stop" ></view>, adding.Stop directly to the method to be used is invalid
  • Do not introduce large js. If it is more than 500k, the tool will give a prompt when compiling
  • For example, in the region selection control, province, city and region are three interfaces. Avoid rolling listening to the request interface data. When listening to the rolling events of scroll view, the view layer will frequently send data to the logic layer

10. To be solved and considered

  • For closing a page and returning to the previous page, you need to transfer data. How to operate effectively?
  • If each item in the long list has a add to cart button, how can I not refresh the whole list after clicking the number + 1?

Keywords: Front-end network JSON Android Vue

Added by astaroth on Sun, 24 May 2020 05:12:06 +0300