当前位置:网站首页>Uni app learning record -- 1. Uni app basic grammar

Uni app learning record -- 1. Uni app basic grammar

2020-11-13 03:42:14 Relieving Sichuan

List of articles

1.uni-app Basic use of

1.1 Learning route

  • Environment building
  • Page appearance configuration
  • Data binding
  • uni-app Life cycle of
  • Use of components
  • uni-app Chinese style learning
  • stay uni-app Use font icons and turn on scss
  • Conditional annotations are cross end compatible
  • uni In the event
  • Navigation jump
  • Component creation and communication , And the life cycle of the component
  • uni-app Use in uni-ui library

project : Black horse mall project

1.2 uni-app Introduce

Official website

uni-app It's a use Vue.js Develop a framework for all front-end applications , Developers write a set of code , Can be posted to iOS、Android、H5、 And all kinds of little programs ( WeChat / Alipay / Baidu / headlines /QQ/ nailing ) Wait for multiple platforms .

Even if it doesn't span ends ,uni-app At the same time, it is a better framework for small program development .

have vue And wechat applet development experience , But get started quickly uni-app

Why study uni-app?

Relative to developers , Reduced learning costs , Because only learn to uni-app after , You can develop iOS、Android、H5、 And the application of various small programs , There's no need to learn to develop frameworks for other applications , Relative to the company , It also greatly reduces development costs .

1.3 Environment building

Install editor HbuilderX Download address

HBuilderX It's a common front-end development tool , But for uni-app Made a special enhancement .

download App Development Edition , It can be used out of the box

Install wechat developer tools Download address

1.4 utilize HbuilderX Initialize project

  • Click on HbuilderX Menu bar file > project > newly build

  • choice uni-app, Fill in the project name , Project created Directory

 Insert picture description here

1.5 Run the project

Click Run in the menu bar , Run to browser , Select a browser to run

Running in wechat developer tool : Get into hello-uniapp project , Click on the toolbar to run -> Run to the applet Simulator -> WeChat developer tools , You can experience it in the wechat developer tool uni-app

Running in wechat developer tool : Get into hello-uniapp project , Click on the toolbar to run -> Run to cell phone or Simulator -> Choose the mode of mobile phone

Be careful :

  • If it's the first time , You need to configure the applet first ide The relevant path of , To run successfully
  • Wechat developer tool security settings in settings , The service port is on

1.6 Introduce the project directory and file function

pages.json Documents are used to correct uni-app Global configuration , Determine the path of the page file 、 Window style 、 The native navigation bar 、 The original at the bottom tabbar etc.

manifest.json File is the configuration file of the application , Used to specify the name of the application 、 Icon 、 Authority, etc .

App.vue It's our heel component , All pages are in App.vue Next to switch , It's a page entry file , You can call the lifecycle function of the application .

main.js It's our project entry file , The main function is to initialize vue Instance and use the required plug-ins .

uni.scss The purpose of the document is to facilitate the overall control of the application style . Like button color 、 Border style ,uni.scss There are a number of preset files scss Variable presets .

unpackage It's the package catalog , Here's the package file for each platform

pages All the pages in the directory

static Static resource directory , For example, pictures, etc

components Component storage directory

In order to achieve multi terminal compatibility , Consider the compilation speed 、 Operation performance and other factors ,uni-app The following development specifications are agreed :

2. Global configuration and page configuration

2.1 adopt globalStyle Global configuration

The status bar used to set the application 、 Navigation bar 、 title 、 Window background color, etc . Detailed documentation

attribute type The default value is describe
navigationBarBackgroundColor HexColor #F7F7F7 Navigation bar background color ( Same as background color of status bar )
navigationBarTextStyle String white Navigation bar title color and status bar foreground color , Support only black/white
navigationBarTitleText String Navigation bar title text content
backgroundColor HexColor #ffffff Background color of window
backgroundTextStyle String dark The drop-down loading The style of , Support only dark / light
enablePullDownRefresh Boolean false Enable pull-down refresh , See Page lifecycle .
onReachBottomDistance Number 50 Distance from the bottom of the page when the pull-up event is triggered , Units only support px, See Page lifecycle

2.2 Create a new message page

Right click pages newly build message Catalog , stay message Right click New in the directory .vue file , And choose the basic template

<template>
	<view>
		 This is the information page 
	</view>
</template>

<script>
</script>

<style>
</style>

2.3 adopt pages To configure the page

attribute type The default value is describe
path String Configure page path
style Object Configure the page window representation , Configuration item reference pageStyle

pages The first item in the array represents the application startup page

"pages": [ 、
		{
			"path":"pages/message/message"
		},
		{
			"path": "pages/index/index",
			"style": {
				"navigationBarTitleText": "uni-app"
			}
		}
	]

adopt style Change page title and navigation bar background color , And set up h5 Drop down refresh unique style

"pages": [ //pages The first item in the array represents the application startup page , Reference resources :https://uniapp.dcloud.io/collocation/pages
		{
    
			"path":"pages/message/message",
			"style": {
    
				"navigationBarBackgroundColor": "#007AFF",
				"navigationBarTextStyle": "white",
				"enablePullDownRefresh": true,
				"disableScroll": true,
				"h5": {
    
					"pullToRefresh": {
    
						"color": "#007AFF"
					}
				}
			}
		}
	]

2.4 To configure tabbar

If the application is more than one tab application , Can pass tabBar Configuration item assignment tab Column performance , as well as tab The corresponding page displayed when switching .

Tips

  • When setting position by top when , Will not show icon
  • tabBar Medium list Is an array , It can only be configured with a minimum of 2 individual 、 most 5 individual tab,tab Sort by array .

Attribute specification :

attribute type Required The default value is describe Platform difference description
color HexColor yes tab The default color of the text on
selectedColor HexColor yes tab The color of the selected text on
backgroundColor HexColor yes tab Background color of
borderStyle String no black tabbar The color of the top border , Support only black/white App 2.3.4+ Support other color values
list Array yes tab A list of , See list Attribute specification , least 2 individual 、 most 5 individual tab
position String no bottom Optional value bottom、top top Value is only supported by wechat applets

among list Receive an array , Each item in the array is an object , Its attribute values are as follows :

attribute type Required explain
pagePath String yes Page path , Must be in pages First of all
text String yes tab Up button text , stay 5+APP and H5 Platform is not required . For example, you can put a word in the middle + Number icon
iconPath String no Picture path ,icon Size limited to 40kb, The recommended size is 81px * 81px, When postion by top when , This parameter is not valid , Network pictures are not supported , Font icons are not supported
selectedIconPath String no The path of the selected image ,icon Size limited to 40kb, The recommended size is 81px * 81px , When postion by top when , This parameter is not valid

Case code :

"tabBar": {
    
		"list": [
			{
    
				"text": " home page ",
				"pagePath":"pages/index/index",
				"iconPath":"static/tabs/home.png",
				"selectedIconPath":"static/tabs/home-active.png"
			},
			{
    
				"text": " Information ",
				"pagePath":"pages/message/message",
				"iconPath":"static/tabs/message.png",
				"selectedIconPath":"static/tabs/message-active.png"
			},
			{
    
				"text": " We ",
				"pagePath":"pages/contact/contact",
				"iconPath":"static/tabs/contact.png",
				"selectedIconPath":"static/tabs/contact-active.png"
			}
		]
	}

2.5 condition Boot mode configuration

Boot mode configuration , Effective during development only , It is used to simulate the scene of direct page , Such as : After the applet is forwarded , The user clicks on the open page .

Attribute specification :

attribute type If required describe
current Number yes Currently active mode ,list The index value of the node
list Array yes Start mode list

list explain :

attribute type If required describe
name String yes Start mode name
path String yes Launch page path
query String no Launch parameters , It can be found in onLoad Function

3. Basic use of components

uni-app It provides rich basic components for developers , Developers can be like building blocks , The combination of various components is called its own application

uni-app Components in , It's like HTML Medium divpspan And the label works the same way , The infrastructure for building pages

3.1 text Usage of text components

3.1.1 text Properties of components

attribute type The default value is Required explain
selectable boolean false no Is text optional
space string . no Show continuous spaces , Optional parameters :enspemspnbsp
decode boolean false no Whether the decoding
  • text Components are equivalent to inline tags 、 Show on the same line
  • Except for text nodes, other nodes cannot be long pressed to select

3.1.2 Code case

<view>
  <!--  Whether long press text is optional  -->
  <text selectable='true'> Here we go. </text>
</view>

<view>
  <!--  How to show consecutive spaces  -->
  <view>
    <text space='ensp'> coming    bro </text>
  </view>
  <view>
    <text space='emsp'> coming    bro </text>
  </view>
  <view>
    <text space='nbsp'> coming    bro </text>
  </view>
</view>

<view>
  <text>skyblue</text>
</view>

<view>
  <!--  Whether the decoding  -->
  <text decode='true'>&nbsp; &lt; &gt; &amp; &apos; &ensp; &emsp;</text>
</view>

3.2 view Usage of view container components

View View container , Be similar to HTML Medium div

3.2.1 Properties of components

 Insert picture description here

3.2.2 Code case

<view class="box2" hover-class="box2_active">
  <view class='box1' hover-class='active' hover-stop-propagation :hover-start-time="2000" :hover-stay-time='2000'>

  </view>
</view>

3.3 button Button component usage

3.3.1 Properties of components

Property name type The default value is explain
size String default Size of button
type String default Style type of button
plain Boolean false Whether the button is hollow , Transparent background color
disabled Boolean false Is it a button
loading Boolean false Does the name carry loading t Icon
  • button By default, the component is exclusive to one line , Set up size by mini You can display multiple

3.3.2 Case code

<button size='mini' type='primary'> front end </button>

<button size='mini' type='default' disabled='true'> front end </button>

<button size='mini' type='warn' loading='true'> front end </button>

3.4 image Use of components

image

picture .

Property name type The default value is explain Platform difference description
src String Picture resource address
mode String ‘scaleToFill’ Image clipping 、 Zoom mode

Tips

  • <image> Default width of component 300px、 Height 225px;
  • src Only relative paths... Are supported 、 Absolute path , Support base64 code ;
  • Complex page structure ,css Too many styles , Use image May cause the style to take effect slowly , appear “ Flash ” The situation of , Now set image{will-change: transform} , This problem can be optimized .

4.uni-app Style in

  • rpx That's reactive px, A dynamic unit that adapts to the screen width . With 750 Wide screen as the benchmark ,750rpx Just the width of the screen . The screen widens ,rpx The actual display effect will be proportionally enlarged .

  • Use @import Statement can import an external stylesheet ,@import Followed by the relative path of the external stylesheet to be imported , use ; End of statement

  • Support basic common selectors class、id、element etc.

  • stay uni-app Cannot be used in * Selectors .

  • page amount to body node

  • It's defined in App.vue The styles in are global styles , For every page . stay pages Under the table of contents Of vue The styles defined in the file are local styles , It only works on the corresponding page , And will cover App.vue The same selector in .

  • uni-app Support for font icons , Usage and common web The project is the same , The following points need to be noted :

    • Font file is less than 40kb,uni-app Will automatically convert it to base64 Format ;

    • Font file is greater than or equal to 40kb, Need to be converted by developers themselves , Otherwise, the use will not take effect ;

    • The reference path of the font file is recommended to use ~@ The absolute path at the beginning .

       @font-face {
           font-family: test1-icon;
           src: url('~@/static/iconfont.ttf');
       }
      
  • How to use scss perhaps less: stay style Use in Tags lang="scsc" perhaps lang="less" To declare that the style turns on these two properties

5.uni-app Data binding in

Data needs to be defined in the page , And before us vue It's the same , Directly in data Define the data in

export default {
    
  data () {
    
    return {
    
      msg: 'hello-uni'
    }
  }
}

5.1 The use of interpolation expressions

  • Using interpolation expressions to render basic data

    <view>{
         {msg}}</view>
    
  • Using ternary operations in interpolation expressions

    <view>{
         { flag ? ' I'm real ':' I'm a fake ' }}</view>
    
  • Basic operation

    <view>{
         {1+1}}</view>
    

5.2 v-bind Dynamic binding properties

stay data A picture is defined in , We want to render this image on the page

export default {
    
  data () {
    
    return {
    
      img: 'http://destiny001.gitee.io/image/monkey_02.jpg'
    }
  }
}

utilize v-bind Rendering

<image v-bind:src="img"></image>

It can also be abbreviated to :

<image :src="img"></image>

5.3 v-for Use

data An array is defined in , Finally, the array is rendered to the page

data () {
    
  return {
    
    arr: [
      {
     name: ' Lennon ', age: 29 },
      {
     name: ' Zhao si ', age: 39 },
      {
     name: ' Song Xiaobao ', age: 49 },
      {
     name: ' Little Shenyang ', age: 59 }
    ]
  }
}

utilize v-for Cycle through

<view v-for="(item,i) in arr" :key="i"> name :{
    {
    item.name}}--- Age :{
    {
    item.age}}</view>

6.uni-app In the event

6.1 Event binding

stay uni Event binding and vue It's the same in , adopt v-on Binding events , Or we could just write it as @

<button @click="tapHandle"> Point me </button>

Event functions are defined in methods in

methods: {
    
  tapHandle () {
    
    console.log(' Really ordered me ')
  }
}

6.2 Event biography

  • By default, if no parameters are passed , The first formal parameter of the event function is the event object

    // template
    <button @click="tapHandle"> Point me </button>
    // script
    methods: {
      tapHandle (e) {
        console.log(e)
      }
    }
    
  • If you pass an argument to an event function , Then the corresponding event function parameter receives the data passed over

    // template
    <button @click="tapHandle(1)"> Point me </button>
    // script
    methods: {
      tapHandle (num) {
        console.log(num)
      }
    }
    
  • If you get an event object, you also want to pass parameters

    // template
    <button @click="tapHandle(1,$event)"> Point me </button>
    // script
    methods: {
      tapHandle (num,e) {
        console.log(num,e)
      }
    }
    

7.uni-app Life cycle of

7.1 The life cycle of the application

Concept of life cycle : An object is created from 、 function 、 The whole process of destruction is called the life cycle .

Life cycle function : In the life cycle, each stage will be accompanied by the triggering of each function , These functions are called lifecycle functions

uni-app Support the following application lifecycle functions :

Function name explain
onLaunch When uni-app Triggered when initialization is complete ( Global trigger only once )
onShow When uni-app start-up , Or enter the foreground display from the background
onHide When uni-app From the front to the back
onError When uni-app Trigger when an error is reported

7.2 The life cycle of a page

uni-app The following page lifecycle functions are supported :

Function name explain Platform difference description Minimum version
onLoad Monitor page loading , Its parameter is the data passed from the previous page , Parameter type is Object( For page reference ), Reference resources Example
onShow Monitor page display . Every time a page appears on the screen, it triggers , This includes returning from the lower page to expose the current page
onReady Listening page first rendering completed .
onHide Monitor page hidden
onUnload Monitor page uninstall

8.uni-app Drop down to refresh & Pull on loading

8.1 The drop-down refresh

8.1.1 Turn on pull-down refresh

stay uni-app There are two ways to turn on the drop-down refresh

  • Need to be in pages.json in , Of the current page found pages node , And in style Option on enablePullDownRefresh
  • By calling uni.startPullDownRefresh Method to turn on the drop-down refresh

8.1.1.1 Open... Via configuration file

establish list Page to demonstrate

<template>
	<view>
		 Hangzhou discipline 
		<view v-for="(item,index) in arr" :key="index">
			{
   {item}}
		</view>
	</view>
</template>

<script>
	export default {
     
		data () {
     
			return {
     
				arr: [' front end ','java','ui',' big data ']
			}
		}
	}
</script>

<style>
</style>

adopt pages.json Find the current page in the file pages node , And in style Option on enablePullDownRefresh

{
    
  "path":"pages/list/list",
    "style":{
    
      "enablePullDownRefresh": true
    }
}

8.1.1.2 adopt API Turn on

api file

uni.startPullDownRefresh()

8.1.2 Listen to drop-down refresh

adopt onPullDownRefresh You can listen to the pull-down refresh action

export default {
    
  data () {
    
    return {
    
      arr: [' front end ','java','ui',' big data ']
    }
  },
  methods: {
    
    startPull () {
    
      uni.startPullDownRefresh()
    }
  },
  onPullDownRefresh () {
    
    console.log(' Trigger pull down to refresh ')
  }
}

8.1.3 Turn off pull-down refresh

uni.stopPullDownRefresh()

Stop the current page drop-down refresh .

Case presentation

<template>
	<view>
		<button type="primary" @click="startPull"> Turn on pull-down refresh </button>
		 Hangzhou discipline 
		<view v-for="(item,index) in arr" :key="index">
			{
   {item}}
		</view>
	</view>
</template>
<script>
	export default {
     
		data () {
     
			return {
     
				arr: [' front end ','java','ui',' big data ']
			}
		},
		methods: {
     
			startPull () {
     
				uni.startPullDownRefresh()
			}
		},
		
		onPullDownRefresh () {
     
			this.arr = []
			setTimeout(()=> {
     
				this.arr = [' front end ','java','ui',' big data ']
				uni.stopPullDownRefresh()
			}, 1000);
		}
	}
</script>

8.2 Pull on loading

By means of pages.json Find the current page in the file pages Under the node style Middle configuration onReachBottomDistance You can set the distance from the bottom to start loading , The default is 50px

adopt onReachBottom Monitoring the behavior of hitting the bottom

<template>
	<view>
		<button type="primary" @click="startPull"> Turn on pull-down refresh </button>
		 Hangzhou discipline 
		<view v-for="(item,index) in arr" :key="index">
			{
    {
    item}}
		</view>
	</view>
</template>
<script>
	export default {
    
		data () {
    
			return {
    
				arr: [' front end ','java','ui',' big data ',' front end ','java','ui',' big data ']
			}
		},
		onReachBottom () {
    
			console.log(' It's bottomed out ')
		}
	}
</script>

<style>
	view{
    
		height: 100px;
		line-height: 100px;
	}
</style>

9. Network request

stay uni Can be called uni.request Method to request a network request

It should be noted that : In applets, network related API You need to configure the domain name white list before use .

9.1 send out get request

<template>
	<view>
		<button @click="sendGet"> Send a request </button>
	</view>
</template>
<script>
	export default {
    
		methods: {
    
			sendGet () {
    
				uni.request({
    
					url: 'http://localhost:8082/api/getlunbo',
					success(res) {
    
						console.log(res)
					}
				})
			}
		}
	}
</script>

9.2 send out post request

send out post Request and send get The request steps are similar to , Here you can refer to the official documents , No more details here .

10. Data caching

10.1 uni.setStorage

Official documents

Store the data in the local cache specified key in , Will cover up the original key Corresponding content , This is an asynchronous interface .

Code demonstration

<template>
	<view>
		<button type="primary" @click="setStor"> Store the data </button>
	</view>
</template>

<script>
	export default {
    
		methods: {
    
			setStor () {
    
				uni.setStorage({
    
				 	key: 'id',
				 	data: 100,
				 	success () {
    
				 		console.log(' Storage success ')
				 	}
				 })
			}
		}
	}
</script>

<style>
</style>

10.2 uni.setStorageSync

take data Store... Specified in the local cache key in , Will cover up the original key Corresponding content , This is a synchronous interface .

Code demonstration

<template>
	<view>
		<button type="primary" @click="setStor"> Store the data </button>
	</view>
</template>

<script>
	export default {
    
		methods: {
    
			setStor () {
    
				uni.setStorageSync('id',100)
			}
		}
	}
</script>

<style>
</style>

10.3 uni.getStorage

Asynchronously get the specified... From the local cache key Corresponding content .

Code demonstration

<template>
	<view>
		<button type="primary" @click="getStorage"> get data </button>
	</view>
</template>
<script>
	export default {
     
		data () {
     
			return {
     
				id: ''
			}
		},
		methods: {
     
			getStorage () {
     
				uni.getStorage({
     
					key: 'id',
					success:  res=>{
     
						this.id = res.data
					}
				})
			}
		}
	}
</script>

10.4 uni.getStorageSync

Get the specified from the local cache synchronously key Corresponding content .

Code demonstration

<template>
	<view>
		<button type="primary" @click="getStorage"> get data </button>
	</view>
</template>
<script>
	export default {
     
		methods: {
     
			getStorage () {
     
				const id = uni.getStorageSync('id')
				console.log(id)
			}
		}
	}
</script>

10.5 uni.removeStorage

Remove the specified from the local cache asynchronously key.

Code demonstration

<template>
	<view>
		<button type="primary" @click="removeStorage"> Delete data </button>
	</view>
</template>
<script>
	export default {
     
		methods: {
     
			removeStorage () {
     
				uni.removeStorage({
     
					key: 'id',
					success: function () {
     
						console.log(' Delete successful ')
					}
				})
			}
		}
	}
</script>

10.6 uni.removeStorageSync

Remove the specified from the local cache synchronously key.

Code demonstration

<template>
	<view>
		<button type="primary" @click="removeStorage"> Delete data </button>
	</view>
</template>
<script>
	export default {
     
		methods: {
     
			removeStorage () {
     
				uni.removeStorageSync('id')
			}
		}
	}
</script>

11. To upload pictures & The preview image

11.1 To upload pictures

uni.chooseImage Methods select pictures from the local album or take pictures with the camera .

Case code

<template>
	<view>
		<button @click="chooseImg" type="primary"> To upload pictures </button>
		<view>
			<image v-for="item in imgArr" :src="item" :key="index"></image>
		</view>
	</view>
</template>

<script>
	export default {
     
		data () {
     
			return {
     
				imgArr: []
			}
		},
		methods: {
     
			chooseImg () {
     
				uni.chooseImage({
     
					count: 9,
					success: res=>{
     
						this.imgArr = res.tempFilePaths
					}
				})
			}
		}
	}
</script>

11.2 The preview image

structure

<view>
	<image v-for="item in imgArr" :src="item" @click="previewImg(item)" :key="item"></image>
</view>

How to preview pictures

previewImg (current) {
    
  uni.previewImage({
    
    urls: this.imgArr,
    current
  })
}

12. Conditional annotation realizes cross segment compatibility

Conditional compilation is marked with special comments , Based on these special comments at compile time , Compile the code in the comments to different platforms .

How to write it : With #ifdef Add platform logo start , With #endif ending .

Platform logo

value platform Reference documents
APP-PLUS 5+App HTML5+ standard
H5 H5
MP-WEIXIN Wechat applet Wechat applet
MP-ALIPAY Alipay applet Alipay applet
MP-BAIDU Baidu applet Baidu applet
MP-TOUTIAO Headline widget Headline widget
MP-QQ QQ Applet ( At present, only cli Version support )
MP Wechat applet / Alipay applet / Baidu applet / Headline widget /QQ Applet

12.1 Conditional comments for components

Code demonstration

<!-- #ifdef H5 -->
<view>
  h5 The page will show 
</view>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<view>
   Wechat applet will show 
</view>
<!-- #endif -->
<!-- #ifdef APP-PLUS -->
<view>
  app Will be displayed 
</view>
<!-- #endif -->

12.2 api The condition note of

Code demonstration

onLoad () {
    
  //#ifdef MP-WEIXIN
  console.log(' Wechat applet ')
  //#endif
  //#ifdef H5
  console.log('h5 page ')
  //#endif
}

Conditional annotation of style

Code demonstration

/* #ifdef H5 */
view{
    
  height: 100px;
  line-height: 100px;
  background: red;
}
/* #endif */
/* #ifdef MP-WEIXIN */
view{
    
  height: 100px;
  line-height: 100px;
  background: green;
}
/* #endif */

13.uni-app Navigation jump in

13.1 utilize navigator To jump

navigator Detailed documentation : Document address

Jump to the normal page

<navigator url="/pages/about/about" hover-class="navigator-hover">
  <button type="default"> Jump to about page </button>
</navigator>

Jump to tabbar page

<navigator url="/pages/message/message" open-type="switchTab">
  <button type="default"> Jump to message page </button>
</navigator>

13.2 Jump with programmed navigation

Navigation jump document

utilize navigateTo Make navigation jump

Keep the current page , Jump to a page in the app , Use uni.navigateBack You can go back to the original page .

<button type="primary" @click="goAbout"> Jump to about page </button>

adopt navigateTo Method to jump to the normal page

goAbout () {
    
  uni.navigateTo({
    
    url: '/pages/about/about',
  })
}

adopt switchTab Jump to tabbar page

Jump to tabbar page

<button type="primary" @click="goMessage"> Jump to message page </button>

adopt switchTab Method to jump

goMessage () {
    
  uni.switchTab({
    
    url: '/pages/message/message'
  })
}

redirectTo To jump

Close current page , Jump to a page in the app .

<!-- template -->
<button type="primary" @click="goMessage"> Jump to message page </button>
<!-- js -->
goMessage () {
  uni.switchTab({
    url: '/pages/message/message'
  })
}

adopt onUnload Test that the current component is actually unloaded

onUnload () {
    
  console.log(' The component is unloaded ')
}

13.3 Navigation jump pass parameters

While navigating to jump to the next page , You can pass the corresponding parameters to the next page , The page that receives the parameters can be accessed through onLoad Life cycle to receive

The page that passes the parameters

goAbout () {
    
  uni.navigateTo({
    
    url: '/pages/about/about?id=80',
  });
}

Page to receive parameters

<script>
	export default {
    
		onLoad (options) {
    
			console.log(options)
		}
	}
</script>

14.uni-app The creation of components in

stay uni-app in , You can create a suffix named vue The file of , That is, a component is created successfully , Other components can use this component through impot How to import , Through components Just register

  • establish login Components , stay component Created in login Catalog , Then build login.vue file

    <template>
    	<view>
    		 This is a custom component 
    	</view>
    </template>
    
    <script>
    </script>
    
    <style>
    </style>
    
  • Import the component into other components and register

    import login from "@/components/test/test.vue"
    
  • Certified components

    components: {
          test}
    
  • Use components

    <test></test>
    

The life cycle function of the component

beforeCreate Called after instance initialization . See
created Called immediately after the instance is created . See
beforeMount Called before the mount begins . See
mounted When mounted to an instance, it is called . See Be careful : It's not sure that all the subcomponents are mounted here , If you need a child component to be completely mounted, you can use $nextTickVue Official documents
beforeUpdate Call... When data is updated , It happens in the virtual DOM Before patching . See only H5 Platform support
updated Virtual due to data changes DOM Re rendering and patching , The hook is called after this . See only H5 Platform support
beforeDestroy Call before instance destruction . In this step , Instance is still fully available . See
destroyed Vue Call after instance destruction . After calling ,Vue Everything indicated by the instance is unbound , All event listeners will be removed , All child instances will also be destroyed . See

15. Communication of components

15.1 The parent component passes values to the child component

adopt props To accept values passed from the outside to the inside of the component

<template>
	<view>
		 This is a custom component  {
   {msg}}
	</view>
</template>

<script>
	export default {
		props: ['msg']
	}
</script>

<style>
</style>

Other components are using login When the component is passed a value

<template>
	<view>
		<test :msg="msg"></test>
	</view>
</template>

<script>
	import test from "@/components/test/test.vue"
	export default {
		data () {
			return {
				msg: 'hello'
			}
		},
		
		components: {test}
	}
</script>

15.2 Child components pass values to parent components

adopt $emit Trigger event to pass parameters

<template>
	<view>
		 This is a custom component  {
   {msg}}
		<button type="primary" @click="sendMsg"> Pass value... To parent component </button>
	</view>
</template>

<script>
	export default {
     
		data () {
     
			return {
     
				status: ' To play basketball '
			}
		},
		props: {
     
			msg: {
     
				type: String,
				value: ''
			}
		},
		methods: {
     
			sendMsg () {
     
				this.$emit('myEvent',this.status)
			}
		}
	}
</script>

The parent component defines custom events and receives parameters

<template>
	<view>
		<test :msg="msg" @myEvent="getMsg"></test>
	</view>
</template>
<script>
	import test from "@/components/test/test.vue"
	export default {
     
		data () {
     
			return {
     
				msg: 'hello'
			}
		},
		methods: {
     
			getMsg (res) {
     
				console.log(res)
			}
		},
		
		components: {
     test}
	}
</script>

15.3 Brother component Communications

Similar to the above two situations , It needs to be discussed on a case by case basis , No more details here .

16.uni-ui Use

uni-ui file

1、 Get into Grid Grid components

2、 Use HBuilderX Import the component

3、 Import the component

import uniGrid from "@/components/uni-grid/uni-grid.vue"
import uniGridItem from "@/components/uni-grid-item/uni-grid-item.vue"

4、 Certified components

components: {uniGrid,uniGridItem}

5、 Use components

<uni-grid :column="3">
  <uni-grid-item>
    <text class="text"> Text </text>
  </uni-grid-item>
  <uni-grid-item>
    <text class="text"> Text </text>
  </uni-grid-item>
  <uni-grid-item>
    <text class="text"> Text </text>
  </uni-grid-item>
</uni-grid>

版权声明
本文为[Relieving Sichuan]所创,转载请带上原文链接,感谢

随机推荐