uniapp Basics

Posted by ame12 on Mon, 07 Mar 2022 23:20:37 +0100

####Basic use of uni app

Course introduction:

Basic part:

  • Environment construction
  • Page appearance configuration
  • Data binding
  • The life cycle of uni app
  • Use of components
  • Style learning in uni app
  • Using Font Icon and opening scss in uni app
  • Conditional annotation cross end compatibility
  • Events in uni
  • Navigation jump
  • Component creation and communication, and component life cycle
  • Using the uni UI Library in the uni app

Project: dark horse mall project

Introduction to uni app Official website

Uni app is a Vue.js Development of all front-end application frameworks, developers write a set of code, can be released to iOS, Android, H5, and a variety of small programs (WeChat / Alipay / Baidu / headline /QQ/ nail) and other platforms.

Uni app is also a better applet development framework even if it is not cross end.

With vue and wechat applet development experience, you can quickly get started with uni app

Why learn uni app?

Compared with developers, it reduces the learning cost, because after only learning uni app, you can develop iOS, Android, H5 and various applet applications. You don't need to learn the framework of developing other applications. Compared with companies, it also greatly reduces the development cost.

Environment construction

Install editor HbuilderX Download address

HBuilderX is a general-purpose front-end development tool, but it is specially strengthened for uni app.

Download the App development version, which can be used out of the box

Install wechat developer tools Download address

Initializing projects with HbuilderX
  • Click HbuilderX menu bar File > Project > new

  • Select uni app, fill in the project name and the directory created by the project

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-FNtw1emf-1618359880902)(./images/create.jpg)]

Run project

Click Run in the menu bar to run to the browser, and select the browser to run

Run in wechat developer tool: enter the Hello uniapp project, click Run in the toolbar - > run to applet simulator - > wechat developer tool to experience uni app in wechat developer tool

Run in wechat developer tool: enter the Hello uniapp project, click Run in the toolbar - > run to mobile phone or simulator - > select the mobile phone with mode

be careful:

  • If it is used for the first time, you need to configure the relevant path of the applet ide before it can run successfully
  • Wechat developer tool security settings in settings, service port open
Introduce the function of project directory and file

pages.json file is used to globally configure the uni app and determine the path of the page file, window style, native navigation bar, native tabbar at the bottom, etc

manifest.json file is the configuration file of the application, which is used to specify the name, icon, permission, etc. of the application.

App.vue is our follow-up component, and all pages are in app The page entry file is used for switching under Vue, and the application life cycle function can be called.

main.js is our project entry file. Its main function is to initialize the vue instance and use the required plug-ins.

uni. The purpose of scss file is to facilitate the overall control of application style. For example, button color, border style, uni A number of scss variables are preset in the scss file.

unpackage is the packaging directory, where there are packaging files of various platforms

Pages all pages are stored in the directory

Static static resource directory, such as pictures, etc

components component storage directory

In order to realize multi terminal compatibility and comprehensively consider the compilation speed, operation performance and other factors, uni app has agreed on the following development specifications:

  • Page file follow Vue single file component (SFC) specification
  • The component label is close to the applet specification, see Uni app component specification
  • The interface capability (JS API) is close to the wechat applet specification, but the prefix wx needs to be replaced with uni. See Uni app interface specification
  • Data binding and event processing are the same as Vue JS specification, while supplementing the life cycle of App and page
  • In order to be compatible with multi terminal operation, it is recommended to use flex layout for development

Global configuration and page configuration

Global configuration through globalStyle

Used to set the status bar, navigation bar, title, window background color, etc. of the application. Detailed documentation

attributetypeDefault valuedescribe
navigationBarBackgroundColorHexColor#F7F7F7Navigation bar background color (same as status bar background color)
navigationBarTextStyleStringwhiteNavigation bar title color and status bar foreground color, only black/white is supported
navigationBarTitleTextStringNavigation bar title text content
backgroundColorHexColor#ffffffThe background color of the window
backgroundTextStyleStringdarkThe style of drop-down loading only supports dark / light
enablePullDownRefreshBooleanfalseWhether to enable pull-down refresh, see Page lifecycle.
onReachBottomDistanceNumber50The distance from the bottom of the page when the bottom pull event is triggered. The unit only supports px. See Page lifecycle
Create a new message page

Right click to create a new directory under. Messages vue file and select the basic template

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

<script>
</script>

<style>
</style>
Configure pages through pages
attributetypeDefault valuedescribe
pathStringConfigure page path
styleObjectConfiguration page window performance, configuration item reference pageStyle

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

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

Modify the title of the page and the background color of the navigation bar through style, and set the unique style of h5 drop-down refresh

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

If the application is a multi tab application, you can specify the performance of the tab bar and the corresponding page displayed during tab switching through the tabBar configuration item.

Tips

  • When position is set to top, icon will not be displayed
  • The list in the tabBar is an array, which can only be configured with at least 2 and at most 5 tabs. The tabs are sorted in the order of the array.

Attribute description:

attributetypeRequiredDefault valuedescribePlatform difference description
colorHexColoryesDefault color of text on tab
selectedColorHexColoryesThe color when the text on the tab is selected
backgroundColorHexColoryesBackground color of tab
borderStyleStringnoblackThe color of the upper border of tabbar. Only black/white is supportedApp 2.3.4 + supports other color values
listArrayyesFor the list of tabs, see the description of the list attribute. There are at least 2 and at most 5 tabs
positionStringnobottomThe optional values are bottom and topThe top value is only supported by wechat applets

list receives an array. Each item in the array is an object, and its attribute values are as follows:

attributetypeRequiredexplain
pagePathStringyesThe page path must be defined in pages first
textStringyesThe button text on the tab is not required on the 5+APP and H5 platforms. For example, a + icon without text can be placed in the middle
iconPathStringnoImage path. The icon size is limited to 40kb. The recommended size is 81px * 81px. When the position is top, this parameter is invalid. Network images and font icons are not supported
selectedIconPathStringnoWhen selected, the icon size is limited to 40kb, and the recommended size is 81px * 81px. When the position is top, this parameter is invalid

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"
			}
		]
	}
condition startup mode configuration

Startup mode configuration, which only takes effect during development, is used to simulate the scene of direct access to the page, such as: after the applet is forwarded, the user clicks the open page.

Attribute description:

attributetypeRequireddescribe
currentNumberyesThe currently active mode, the index value of the list node
listArrayyesStartup mode list

list description:

attributetypeRequireddescribe
nameStringyesStartup mode name
pathStringyesLaunch path page
queryStringnoStartup parameters can be found in the onLoad Get in function

Basic use of components

Uni app provides rich basic components for developers. Developers can combine various components to assemble their own applications like building blocks

Components in uni app, like tags such as div, p and span in HTML, are used to build the basic structure of the page

text component usage
001 - properties of the text component
attributetypeDefault valueRequiredexplain
selectablebooleanfalsenoText optional
spacestring.noDisplay continuous spaces, optional parameters: ensp, emsp, nbsp
decodebooleanfalsenoDecode
  • The text component is equivalent to an in line label and is displayed on the same line
  • Nodes other than text nodes cannot be selected by long pressing
002 - Code Case
<view>
  <!-- Long press text to select -->
  <text selectable='true'>Here we are, brother</text>
</view>

<view>
  <!-- How to display consecutive spaces -->
  <view>
    <text space='ensp'>Here we are, brother</text>
  </view>
  <view>
    <text space='emsp'>Here we are, brother</text>
  </view>
  <view>
    <text space='nbsp'>Here we are, brother</text>
  </view>
</view>

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

<view>
  <!-- Decode -->
  <text decode='true'>&nbsp; &lt; &gt; &amp; &apos; &ensp; &emsp;</text>
</view>
Usage of view container component

View view container, similar to div in HTML

001 - properties of components

[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-KzXjeVto-1618359880905)(./images/2view.png)]

002 - 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>
Usage of button component
001 - properties of components
Attribute nametypeDefault valueexplain
sizeStringdefaultButton size
typeStringdefaultStyle type of button
plainBooleanfalseWhether the button is hollow and the background color is transparent
disabledBooleanfalseWhether button
loadingBooleanfalseDoes the name have a loading t icon
  • By default, the button component is exclusive in one line. When the size is set to mini, multiple buttons can be displayed in one line
002 - 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>
Use of image components
image

Picture.

Attribute nametypeDefault valueexplainPlatform difference description
srcStringPicture resource address
modeString'scaleToFill'Picture clipping and zooming mode

Tips

  • < Image > the default width of the component is 300px and the height is 225px;
  • src only supports relative path and absolute path, and supports base64 code;
  • When the page structure is complex and there are too many css styles, using image may cause the style to take effect slowly and "flash". At this time, setting image {will change: Transform} can optimize this problem.

Styles in uni app

  • Rpx is responsive px, a dynamic unit that adapts to the screen width. Based on the 750 wide screen, 750 rpx is exactly the screen width. As the screen becomes wider, the rpx actual display effect will be magnified in equal proportion.

  • Use the @ import statement to import the external style sheet, @ import followed by the relative path of the external style sheet to be imported, with; Indicates the end of the statement

  • Support basic and common selectors such as class, id, element, etc

  • The * selector cannot be used in a uni app.

  • page is equivalent to the body node

  • Defined in app The style in vue is a global style, which acts on every page. The style defined in the vue file under the pages directory is a local style, which only works on the corresponding page and will overwrite the app The same selector in vue.

  • Uni app supports the use of font icons in the same way as ordinary web projects. Note the following:

    • If the font file is less than 40kb, uni app will automatically convert it to base64 format;

    • If the font file is greater than or equal to 40kb, it needs to be converted by the developer, otherwise the use will not take effect;

    • It is recommended to use the absolute path starting with ~ @ for the reference path of font file.

       @font-face {
           font-family: test1-icon;
           src: url('~@/static/iconfont.ttf');
       }
      
  • How to use scss or less

Data binding in uni app

You need to define data in the page. Just like vue before us, you can directly define data in data

export default {
  data () {
    return {
      msg: 'hello-uni'
    }
  }
}
Use of interpolation expressions
  • Rendering basic data using interpolation expressions

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

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

    <view>{{1+1}}</view>
    
v-bind dynamic binding attribute

A picture is defined in data. We want to render this picture to the page

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

Rendering with v-bind

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

It can also be abbreviated to:

<image :src="img"></image>
Use of v-for

Set an array in data, and finally render the array 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 }
    ]
  }
}

Loop with v-for

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

Events in uni

Event binding

Event binding in uni is the same as that in vue. Event binding through v-on can also be abbreviated as@

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

Event functions are defined in methods

methods: {
  tapHandle () {
    console.log('Really order me')
  }
}
Event transmission parameters
  • By default, if no parameters are passed, the first formal parameter of the event function is the event object

    // template
    <button @click="tapHandle">Order me</button>
    // script
    methods: {
      tapHandle (e) {
        console.log(e)
      }
    }
    
  • If the parameter is passed to the event function, the corresponding event function parameter receives the passed data

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

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

The life cycle of uni

Application lifecycle

Concept of life cycle: the whole process of creating, running and destroying an object is called life cycle.

Life cycle functions: each stage in the life cycle will be triggered by each function. These functions are called life cycle functions

Uni app supports the following application lifecycle functions:

Function nameexplain
onLaunchTriggered when uni app initialization is completed (only triggered once globally)
onShowWhen the uni app starts, or enters the foreground display from the background
onHideWhen uni app enters the background from the foreground
onErrorTriggered when uni app reports an error
Page lifecycle

Uni app supports the following page life cycle functions:

Function nameexplainPlatform difference descriptionMinimum version
onLoadListen for page loading. Its parameters are the data transmitted from the previous page. The parameter type is Object (used for page parameter transmission). Refer to Examples
onShowThe listening page is displayed. The page is triggered every time it appears on the screen, including returning from the lower page point to expose the current page
onReadyThe first rendering of the listening page is completed.
onHideListening page hidden
onUnloadListening page unloading

Pull down refresh

Enable pull-down refresh

There are two ways to enable pull-down refresh in uni app

  • Need to be in pages JSON, find the pages node of the current page and turn on enablePullDownRefresh in the style option
  • By calling Uni The startpulldownrefresh method is used to start the pull-down refresh
Open via profile

Create a 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>

Through pages Find the pages node of the current page in the JSON file and turn on enablePullDownRefresh in the style option

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

api documentation

uni.startPullDownRefresh()
Listening pull-down refresh

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

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

uni.stopPullDownRefresh()

Stop the current page pull-down refresh.

Case demonstration

<template>
	<view>
		<button type="primary" @click="startPull">Enable 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>

Pull up loading

Through in pages JSON file. Under the pages node of the current page, configure onReachBottomDistance in style. You can set the distance from the bottom to start loading. The default is 50px

Monitor bottom touching behavior through onReachBottom

<template>
	<view>
		<button type="primary" @click="startPull">Enable 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('Bottomed out')
		}
	}
</script>

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

Network request

In uni, you can call Uni The request method makes a network request

It should be noted that in the applet, the network related API needs to configure the domain name white list before use.

Send get request

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

Send post request

Data cache

uni.setStorage

Official documents

Storing data in the key specified in the local cache will overwrite the content corresponding to the original key. This is an asynchronous interface.

Code demonstration

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

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

<style>
</style>
uni.setStorageSync

Storing data in the key specified in the local cache will overwrite the content corresponding to the original key. This is a synchronization interface.

Code demonstration

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

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

<style>
</style>
uni.getStorage

Asynchronously obtain the content corresponding to the specified key from the local cache.

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>
uni.getStorageSync

Synchronously obtain the content corresponding to the specified key from the local cache.

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>
uni.removeStorage

Asynchronously removes the specified key from the local cache.

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('Deleted successfully')
					}
				})
			}
		}
	}
</script>
uni.removeStorageSync

Synchronously removes the specified key from the local cache.

Code demonstration

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

Upload pictures and preview pictures

Upload pictures

uni. The chooseimage method selects a picture from a local album or takes a picture with a camera.

Case code

<template>
	<view>
		<button @click="chooseImg" type="primary">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>
preview pictures

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
  })
}

Conditional annotation for cross segment compatibility

Conditional compilation uses special comments as markers, and compiles the code in the comments to different platforms according to these special comments during compilation.

**Writing method: * * starts with #ifdef and ends with #endif.

Platform identification

valueplatformReference documents
APP-PLUS5+AppHTML5 + specification
H5H5
MP-WEIXINWechat appletWechat applet
MP-ALIPAYAlipay appletAlipay applet
MP-BAIDUBaidu appletBaidu applet
MP-TOUTIAOHeadline appletHeadline applet
MP-QQQQ applet(currently only supported by cli version)
MPWeChat Applet / Alipay Applet / Baidu Applet / headline applet /QQ applet
Conditional comments for components

Code demonstration

<!-- #ifdef H5 -->
<view>
  h5 The page displays
</view>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<view>
  Wechat applet will display
</view>
<!-- #endif -->
<!-- #ifdef APP-PLUS -->
<view>
  app Will show
</view>
<!-- #endif -->
Conditional annotation of api

Code demonstration

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

Conditional notes for styles

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 */

Navigation jump in uni

Jump using navigator

navigator details: Document address

Jump to 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>
Jump using programmed navigation

Navigation jump document

Navigation jump using navigateTo

Keep the current page, jump to a page in the application, and use Uni Navigateback can return to the original page.

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

Jump to the normal page through the navigateTo method

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

Jump to tabbar page through switchTab

Jump to tabbar page

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

Jump through switchTab method

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

redirectTo jump

Close the current page and jump to a page in the application.

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

Through onUnload test, the current component is indeed unloaded

onUnload () {
  console.log('Component uninstalled')
}
Navigation jump transfer parameters

When the navigation jumps to the next page, the corresponding parameters can be passed to the next page, and the page receiving the parameters can be received through the onLoad life cycle

Page passing parameters

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

Page to receive parameters

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

Creation of components in uni app

In uni app, you can create a file with the suffix vue, that is, you can create a component successfully. Other components can import the component through MPOT and register it through components

  • Create a login component, create a login directory in the component, and then create a new login Vue file

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

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

    components: {test}
    
  • Using components

    <test></test>
    
Component lifecycle function
beforeCreateCalled after instance initialization. See details
createdCalled immediately after the instance is created. See details
beforeMountCalled before mount starts. See details
mountedWhen mounted to an instance, it is called. See details Note: it is not certain that the sub components are all mounted here. If you need to fully mount the sub components, you can use $nextTick after performing the operation Vue official documents
beforeUpdateCalled during data update, which occurs before the virtual DOM is patched. See detailsOnly supported by H5 platform
updatedThe hook is called after the virtual DOM is re rendered and patched due to data changes. See detailsOnly supported by H5 platform
beforeDestroyBefore the instance is destroyed, it is called. At this step, the instance is still fully available. See details
destroyedAfter the Vue instance is destroyed, it is called. After calling, everything indicated by the Vue instance will be unbound, all event listeners will be removed, and all sub instances will be destroyed. See details

Communication of components

Parent component passes value to child component

Accept the values passed from the outside to the inside of the component through props

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

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

<style>
</style>

Other components pass values when using the login component

<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>
The child component passes values to the parent component

Pass parameters through the $emit trigger event

<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: '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>
Brother component communication

Use of uni UI

Uni UI document

1. Enter Grid grid components

2. Import the component using HBuilderX

3. Import this component

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

4. Register components

components: {uniGrid,uniGridItem}

5. Using 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>

6. Scroll view: white space: no wrap;