Introduction to uni-appofficial webpage
uni-app
is a program that uses Development of all front-end application framework, developers write a set of code that can be published to iOS, Android, H5, and a variety of small programs (WeChat/Alipay/Baidu/Headline/QQQ/Nail) and other multiple platforms.
Even if it doesn't cross ends.uni-app
It is also a better framework for small program development.
Experience with vue and wechat applet development, can quickly get started with uni-apps
Why go for uni-app learning?
Relative to the developer to reduce the cost of learning, because only after learning uni-app, you can develop iOS, Android, H5, and a variety of small program applications, do not need to learn to develop other applications of the framework, relative to the company, but also greatly reduces the cost of development.
Environment Setup
Installation of the editor HbuilderXdownload address
HBuilderX is the general purpose front-end development tool, but for theuni-app
Special enhancements were made.
Download the App Developer Edition out of the box!
Install WeChat Developer Toolsdownload address
Initializing a project with HbuilderX
-
Click File>Project>New in the HbuilderX menu bar.
-
Select uni-app, fill in the name of the project and the directory where the project is created.
Running Projects
Click Run in the menu bar to run to the browser and select the browser to run it
Run in WeChat Developer Tools: Go to hello-uniapp project, click Run -> Run to Small Program Emulator -> WeChat Developer Tools in the toolbar, you can experience uni-app in WeChat Developer Tools.
Run in WeChat Developer Tools: Go to the hello-uniapp project, click Run in the toolbar -> Run to phone or emulator -> Choose the phone to tune to
Attention:
- If this is the first time you use it, you need to configure the relevant path of the applet ide before you can run it successfully
- WeChat developer tools in the settings of the security settings, service port open
Introducing the role of project directories and files
file is used to globally configure the uni-app, determining the path to page files, window styles, native navigation bar, native tabbar at the bottom, and so on.
A file is a configuration file for an application that specifies the name, icon, permissions, etc. of the application.
is our follow component, and all pages are in the
down for switching is the page entry file, which can call the application's lifecycle functions.
is our project entry file, the main role is to initialize the
vue
instance and use the required plug-ins.
The purpose of the file is to facilitate overall control over the style of the application. For example, button colors, border styles, the
A bunch of scss variable presets are preset in the file.
unpackage
It's the packaging directory, where the packaging files for each platform are located.
pages
Directory where all pages are stored
static
Static resource catalogs, such as images, etc.
components
Component Storage Directory
In order to achieve multi-end compatibility, taking into account factors such as compilation speed and runtime performance, theuni-app
The following development specifications were agreed upon:
- The page file follows theVue Single File Component (SFC) Specification
- Component labels are close to the applet specification, seeuni-app component specification
- The interface capability (JS API) is close to the WeChat applet specification, but you need to prefix the
wx
Replace withuni
For details, seeuni-app interface specification - Data Binding and Event Handling
specification, while complementing the life cycle of apps and pages
- In order to be compatible with multi-terminal operation, it is recommended to use flex layout for development
Global and Page Configuration
Global configuration via globalStyle
Used to set the status bar, navigation bar, title, window background color, etc. of the application.Detailed Documentation
causality | typology | default value | descriptive |
---|---|---|---|
navigationBarBackgroundColor | HexColor | #F7F7F7 | Navigation bar background color (same as status bar background color) |
navigationBarTextStyle | String | white | Navigation bar title color and status bar foreground color, black/white only. |
navigationBarTitleText | String | Navigation bar title text content | |
backgroundColor | HexColor | #ffffff | Background color of the window |
backgroundTextStyle | String | dark | Styles for dropdown loading, only support dark / light |
enablePullDownRefresh | Boolean | false | Whether to enable dropdown refresh, seePage Lifecycle。 |
onReachBottomDistance | Number | 50 | The distance from the bottom of the page when the page pull-up bottom-touch event is triggered, in px only, see thePage Lifecycle |
Create a new message page
Right click pages to create a new message directory, right click under the message directory to create a new .vue file, and select the basic template.
<template>
<view>
This is the information page
</view>
</template>
<script>
</script>
<style>
</style>
Configuring pages via pages
causality | typology | default value | descriptive |
---|---|---|---|
path | String | Configure the page path | |
style | Object | Configuration page window performance, configuration item referencepageStyle |
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 page title and background color of the navigation bar via style, and set the h5 dropdown refresh specific style.
"pages": [ The first item in the //pages array represents the application startup page, see: /collocation/pages
{
"path":"pages/message/message",
"style": {
"navigationBarBackgroundColor": "#007AFF",
"navigationBarTextStyle": "white",
"enablePullDownRefresh": true,
"disableScroll": true,
"h5": {
"pullToRefresh": {
"color": "#007AFF"
}
}
}
}
]
Configuring the tabbar
If the application is a multi-tab application, you can specify how the tab bar behaves and which page is displayed when a tab is switched via the tabBar configuration item.
Tips
- When the position is set to top, the icon will not be displayed.
- The list in tabBar is an array, which can only be configured with a minimum of 2 and a maximum of 5 tabs, and the tabs are sorted in the order of the array.
Property Description:
causality | typology | mandatory field | default value | descriptive | Description of platform differences |
---|---|---|---|---|---|
color | HexColor | be | Default text color on tab | ||
selectedColor | HexColor | be | The color of the text on the tab when it is selected | ||
backgroundColor | HexColor | be | tab's background color | ||
borderStyle | String | clogged | black | The color of the tabbar's upper border, only black/white is supported. | App 2.3.4+ support for other color values |
list | Array | be | A list of tabs, see the description of the list attribute, with a minimum of 2 and a maximum of 5 tabs. | ||
position | String | clogged | bottom | Optional values bottom, top | The top value is only supported by WeChat Small Program |
where list receives an array, and each item in the array is an object with the following attribute values:
causality | typology | mandatory field | clarification |
---|---|---|---|
pagePath | String | be | The path to the page must be defined in pages first |
text | String | be | Button text on tabs is not required on 5+APP and H5 platforms. For example, you can put a + icon in the center with no text. |
iconPath | String | clogged | Image path, icon size limit is 40kb, recommended size is 81px * 81px, when postion is top, this parameter is invalid, does not support network images, does not support font icons |
selectedIconPath | String | clogged | The path of the image when selected, the icon size is limited to 40kb, the recommended size is 81px * 81px, this parameter is invalid when the postion is top. |
Case Code:
"tabBar": {
"list": [
{
"text": "Home",
"pagePath":"pages/index/index",
"iconPath":"static/tabs/",
"selectedIconPath":"static/tabs/"
},
{
"text": "Information",
"pagePath":"pages/message/message",
"iconPath":"static/tabs/",
"selectedIconPath":"static/tabs/"
},
{
"text": "We.",
"pagePath":"pages/contact/contact",
"iconPath":"static/tabs/",
"selectedIconPath":"static/tabs/"
}
]
}
Condition boot mode configuration
Launch mode configuration, effective only during development, is used to simulate direct page scenarios, e.g., the page opened by the user clicking after the applet is forwarded.
Property Description:
causality | typology | Required or not | descriptive |
---|---|---|---|
current | Number | be | Currently active mode, index value of list node |
list | Array | be | List of startup modes |
list description:
causality | typology | Required or not | descriptive |
---|---|---|---|
name | String | be | Startup mode name |
path | String | be | Startup Page Path |
query | String | clogged | The startup parameters, which can be found in the page'sonLoad function to get the |
Basic use of components
uni-app provides a wealth of basic components to developers, developers can be like building blocks, the combination of various components to put together their own applications
Components in the uni-app, like theHTML
hit the nail on the headdiv
、p
、span
etc. tags do the same thing, and are used to build the infrastructure of the page
Usage of the text component
001 - Properties of the text component
causality | typology | default value | mandatory field | clarification |
---|---|---|---|---|
selectable | boolean | false | clogged | Whether the text is optional |
space | string | . | clogged | Displays consecutive spaces with optional parameters:ensp 、emsp 、nbsp
|
decode | boolean | false | clogged | Decode or not |
-
text
Components are equivalent to in-line labels, displayed on the same line - Nodes other than text nodes cannot be selected by long-pressing on them.
002 - Code Cases
<view>
<! -- Is long-pressing text optional -- >!
<text selectable='true'>Here you go, buddy.</text>
</view>
<view>
<! -- A way to display consecutive spaces -- >!
<view>
<text space='ensp'>Here you go, buddy.</text>
</view>
<view>
<text space='emsp'>Here you go, buddy.</text>
</view>
<view>
<text space='nbsp'>Here you go, buddy.</text>
</view>
</view>
<view>
<text>skyblue</text>
</view>
<view>
<! -- whether to decode -->
<text decode='true'> < > & '    </text>
</view>
Usage of the view container component
View A view container, similar to a div in HTML.
001 - Properties of the component
[External link image dump failure, the source site may have anti-piracy chain mechanism, it is recommended to save the image directly uploaded (img-ikPi3LrI-1604244104685) (. /images/)]
002 - Code Cases
<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 the button component
001 - Properties of the component
property name | typology | default value | clarification |
---|---|---|---|
size | String | default | Button size |
type | String | default | Button Style Types |
plain | Boolean | false | Whether the buttons are skeletonized with transparent background color |
disabled | Boolean | false | Whether button |
loading | Boolean | false | Name with or without loading t icon |
-
button
component is exclusive to one line by default, set thesize
because ofmini
You can display more than one
002 - Case Code
<button size='mini' type='primary'>forward part of sth.</button>
<button size='mini' type='default' disabled='true'>forward part of sth.</button>
<button size='mini' type='warn' loading='true'>forward part of sth.</button>
Use of the image component
image
Picture.
property name | typology | default value | clarification | Description of platform differences |
---|---|---|---|---|
src | String | Image Resource Address | ||
mode | String | ‘scaleToFill’ | Patterns for cropping and scaling images |
Tips
-
<image>
The default width of the component is 300px and the height is 225px; -
src
Only support relative path, absolute path, support base64 code; - If the structure of the page is complex and there are too many css styles, using image may cause the style to take effect more slowly, and there will be a "blinking" situation.
image{will-change: transform}
, which can be optimized for this issue.
Styles in uni-app
-
rpx is responsive px, a dynamic unit that adapts to the width of the screen. Taking a 750-wide screen as a base, 750 rpx is exactly the width of the screen. As the screen gets wider, the actual rpx display will be scaled up proportionally.
-
utilization
@import
statement can import outreach stylesheets.@import
followed by the relative path of the outreach stylesheet to be imported with the;
Indicates the end of the statement -
Support for basic common selectors class, id, element, etc.
-
exist
uni-app
You can't use the*
Selector. -
page
equivalent tobody
nodal -
Styles defined in are global and apply to every page. Styles defined in vue files in the pages directory are localized and only apply to the corresponding page, overriding the same selector in the
-
uni-app
Supports the use of font icons in the same way as normalweb
The project is the same and the following points need to be noted:-
Font files are less than 40kb.
uni-app
It is automatically converted to base64 format; -
Fonts larger than or equal to 40kb need to be converted by the developer, otherwise they will not work;
-
It is recommended to use absolute paths starting with ~@ for font file references.
@font-face { font-family: test1-icon; src: url('~@/static/'); }
-
-
How to use scss or less
Data Binding in uni-app
In the page you need to define the data, and our previous vue is exactly the same, define the data directly in the data
export default {
data () {
return {
msg: 'hello-uni'
}
}
}
Use of interpolating expressions
-
Rendering basic data using interpolating expressions
<view>{{msg}}</view>
-
Using ternary operations in interpolating expressions
<view>{{ flag ? 'I'm real':'I'm fake' }}</view>
-
basic operation
<view>{{1+1}}</view>
v-bind dynamic binding properties
An image is defined in data and we want to render this image to the page
export default {
data () {
return {
img: '/image/monkey_02.jpg'
}
}
}
Rendering with v-bind
<image v-bind:src="img"></image>
It can also be abbreviated as.
<image :src="img"></image>
Use of v-for
The data is set to an array, and the array is eventually rendered to the page.
data () {
return {
arr: [
{ name: 'Liu Neng', age: 29 },
{ name: 'Zhao Si', age: 39 },
{ name: 'Song Xiaobao', age: 49 },
{ name: 'Little Shenyang', age: 59 }
]
}
}
Looping 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 in vue, events are bound via v-on, which can also be abbreviated as @
<button @click="tapHandle">Click on me.</button>
Event functions are defined in methods
methods: {
tapHandle () {
console.log('Really clicked me')
}
}
event references
-
By default, if no parameters are passed, the first formal parameter of the event function is the event object.
// template <button @click="tapHandle">Click on me.</button> // script methods: { tapHandle (e) { (e) } }
-
If an event function is passed parameters, the corresponding event function formal parameter receives the passed data.
// template <button @click="tapHandle(1)">Click on me.</button> // script methods: { tapHandle (num) { (num) } }
-
If you get an event object and also want to pass parameters
// template <button @click="tapHandle(1,$event)">Click on me.</button> // script methods: { tapHandle (num,e) { (num,e) } }
Life cycle of uni
Application Life Cycle
The concept of life cycle: the whole process of an object from creation, operation, destruction is become the life cycle.
Lifecycle Functions: Each stage in the lifecycle is accompanied by the triggering of each function, which are called lifecycle functions.
uni-app
The following application life cycle functions are supported:
function name | clarification |
---|---|
onLaunch | (coll.) fail (a student)uni-app Triggered when initialization is complete (only triggered once globally) |
onShow | (coll.) fail (a student)uni-app Launch, or go from the backend to the frontend display |
onHide | (coll.) fail (a student)uni-app Access to the backend from the frontend |
onError | (coll.) fail (a student)uni-app Triggered when an error is reported |
Page Lifecycle
uni-app
The following page life cycle functions are supported:
function name | clarification | Description of platform differences | minimum version |
---|---|---|---|
onLoad | Listen to the page load, its parameters are the data passed on the previous page, the parameter type is Object (used for page passes), refer to thetypical example | ||
onShow | Listens for page displays. Triggered every time a page appears on the screen, including returning from a lower page point to reveal the current page. | ||
onReady | Listens for the initial rendering of the page to complete. | ||
onHide | Listening for page hides | ||
onUnload | Listen for page unloading |
drop-down refresh
Enable drop-down refresh
There are two ways to enable dropdown refresh in uni-apps
- need to be in
in the current page's pages node, and in the
style
Enable in the optionsenablePullDownRefresh
- Enable dropdown refresh by calling the method
Enable via configuration file
Create a list page for demonstration
<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>
Find the pages node for the current page by going through the file in thestyle
The option to turn on theenablePullDownRefresh
{
"path":"pages/list/list",
"style":{
"enablePullDownRefresh": true
}
}
Open via API
api documentation
()
Listen for dropdown refreshes
OnPullDownRefresh allows you to 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('Triggered dropdown refresh now')
}
}
Turn off dropdown refresh
()
Stop the current page drop-down refresh.
Case Demonstration
<template>
<view>
<button type="primary" @click="startPull">Enable drop-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
By finding the current page in the file under the pages node style in the configuration onReachBottomDistance can be set from the bottom of the open loading distance, the default is 50px
Listening for bottoming out via onReachBottom
<template>
<view>
<button type="primary" @click="startPull">Enable drop-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
Methods can be called in uni to request network requests
Note: Network-related APIs in the applet need to be configured with a domain whitelist before use.
Send a 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 a post request
data cache
official document
Storing data in a key specified in the local cache overwrites the original contents of that key, which is an asynchronous interface.
Code Demo
<template>
<view>
<button type="primary" @click="setStor">Stored Data</button>
</view>
</template>
<script>
export default {
methods: {
setStor () {
uni.setStorage({
key: 'id',
data: 100,
success () {
console.log('Stored successfully')
}
})
}
}
}
</script>
<style>
</style>
Storing data in a key specified in the local cache overwrites the original contents of that key, which is a synchronization interface.
Code Demo
<template>
<view>
<button type="primary" @click="setStor">Stored Data</button>
</view>
</template>
<script>
export default {
methods: {
setStor () {
uni.setStorageSync('id',100)
}
}
}
</script>
<style>
</style>
Asynchronously fetches the content corresponding to the specified key from the local cache.
Code Demo
<template>
<view>
<button type="primary" @click="getStorage">Getting data</button>
</view>
</template>
<script>
export default {
data () {
return {
id: ''
}
},
methods: {
getStorage () {
uni.getStorage({
key: 'id',
success: res=>{
this.id = res.data
}
})
}
}
}
</script>
Fetches the content corresponding to the specified key from the local cache synchronously.
Code Demo
<template>
<view>
<button type="primary" @click="getStorage">Getting data</button>
</view>
</template>
<script>
export default {
methods: {
getStorage () {
const id = uni.getStorageSync('id')
console.log(id)
}
}
}
</script>
Removes the specified key from the local cache asynchronously.
Code Demo
<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>
Synchronizes the removal of the specified key from the local cache.
Code Demo
<template>
<view>
<button type="primary" @click="removeStorage">Delete data</button>
</view>
</template>
<script>
export default {
methods: {
removeStorage () {
uni.removeStorageSync('id')
}
}
}
</script>
Upload images, preview images
Upload a picture
Methods Select a picture from a local album or take a picture using the camera.
Case Code
<template>
<view>
<button @click="chooseImg" type="primary">Upload a picture</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 Images
framework
<view>
<image v-for="item in imgArr" :src="item" @click="previewImg(item)" :key="item"></image>
</view>
Method of previewing images
previewImg (current) {
uni.previewImage({
urls: this.imgArr,
current
})
}
Conditional annotations for cross-segment compatibility
Conditional compilation is to use special comments as markers and compile the code inside the comments to different platforms based on these special comments at compile time.
**Writing style:** Starts with #ifdef plus the platform identifier and ends with #endif.
Platform logo
(be) worth | flat-roofed building | reference document |
---|---|---|
APP-PLUS | 5+App | HTML5+ specification |
H5 | H5 | |
MP-WEIXIN | WeChat small program | WeChat small program |
MP-ALIPAY | Alipay applet | Alipay applet |
MP-BAIDU | Baidu applet | Baidu applet |
MP-TOUTIAO | headline-grabbing app | headline-grabbing app |
MP-QQ | QQ applet | (Currently only supported by cli version) |
MP | WeChat applet / Alipay applet / Baidu applet / Headline applet / QQ applet |
Conditional annotations for components
Code Demo
<!-- #ifdef H5 -->
<view>
The h5 page will show
</view>
<!-- #endif -->
<!-- #ifdef MP-WEIXIN -->
<view>
The WeChat applet will show
</view>
<!-- #endif -->
<!-- #ifdef APP-PLUS -->
<view>
The app will show
</view>
<!-- #endif -->
Conditional annotations for api
Code Demo
onLoad () {
//#ifdef MP-WEIXIN
console.log('WeChat Small Program')
//#endif
//#ifdef H5
console.log('h5 page')
//#endif
}
Conditional annotations for styles
Code Demo
/* #ifdef H5 */
view{
height: 100px;
line-height: 100px;
background: red;
}
/* #endif */
/* #ifdef MP-WEIXIN */
view{
height: 100px;
line-height: 100px;
background: green;
}
/* #endif */
Navigational jumps in uni
Jumping with navigator
navigator detailed documentation:file address
Jump to normal page
<navigator url="/pages/about/about" hover-class="navigator-hover">
<button type="default">Jump to the 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>
Jumping around with programmatic navigation
Navigating Jump Documents
Navigational jumps with navigateTo
Keep the current page and jump to a page within the application using theYou can return to the original page.
<button type="primary" @click="goAbout">Jump to the About page</button>
Jump to normal page via navigateTo method
goAbout () {
uni.navigateTo({
url: '/pages/about/about',
})
}
Jump to tabbar page via switchTab
Jump to tabbar page
<button type="primary" @click="goMessage">Jump to message page</button>
Jumping via the switchTab method
goMessage () {
uni.switchTab({
url: '/pages/message/message'
})
}
redirectTo make a jump
Close the current page and jump to a page within the application.
<!-- template -->
<button type="primary" @click="goMessage">Jump to message page</button>
<!-- js -->
goMessage () {
({
url: '/pages/message/message'
})
}
Test that the current component is indeed unloaded with onUnload
onUnload () {
console.log('Component uninstalled')
}
Navigation Jump Passing Parameters
While navigating to the next page, you can pass the appropriate parameters to the next page, and the page that receives the parameters can receive them through the onLoad lifecycle.
Pages passing parameters
goAbout () {
uni.navigateTo({
url: '/pages/about/about?id=80',
});
}
The page that receives the parameter
<script>
export default {
onLoad (options) {
console.log(options)
}
}
</script>
Component creation in uni-app
In uni-app, you can create a file with the suffix vue, that is, create a component successfully, other components can be imported through the impot of the component in the way through the components to register can be
-
To create the login component, create the login directory in component, and then create a new file
<template> <view> This is a custom component </view> </template> <script> </script> </template> <script> </script> </style> </script> <style>.
-
Importing the component in other components and registering it
import login from "@/components/test/"
-
Registered Components
components: {test}
-
Using Components
<test></test>
Component Life Cycle Functions
beforeCreate | Called after the instance has been initialized.for further details, refer to | ||
---|---|---|---|
created | Called immediately after instance creation is complete.for further details, refer to | ||
beforeMount | Called before the start of the mount.for further details, refer to | ||
mounted | Called after mounting on the instance.for further details, refer to Note: This does not confirm that the subcomponent is fully mounted, if you need the subcomponent to be fully mounted before executing the operation you can use the$nextTick Vue Official Documentation
|
||
beforeUpdate | Called on data update, occurs before the virtual DOM is patched.for further details, refer to | Supported by H5 platform only | |
updated | This hook is called after a virtual DOM re-rendering and patching due to data changes.for further details, refer to | Supported by H5 platform only | |
beforeDestroy | Called before the instance is destroyed. At this step, the instance is still fully available.for further details, refer to | ||
destroyed | Called after the Vue instance is destroyed. After the call, everything indicated by the Vue instance is unbound, all event listeners are removed, and all child instances are destroyed.for further details, refer to |
Component communication
Parent component passes value to child component
Accepting values passed from the outside to the inside of a component via 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/"
export default {
data () {
return {
msg: 'hello'
}
},
components: {test}
}
</script>
Passing values from child component to parent component
Passing parameters via $emit trigger event
<template>
<view>
This is a custom component {{msg}}
<button type="primary" @click="sendMsg">Passing values to the parent component</button>
</view>
</template>
<script>
export default {
data () {
return {
status: 'Playing basketball'
}
},
props: {
msg: {
type: String,
value: ''
}
},
methods: {
sendMsg () {
this.$emit('myEvent',this.status)
}
}
}
</script>
Parent component defines custom events and receives parameters
<template>
<view>
<test :msg="msg" @myEvent="getMsg"></test>
</view>
</template>
<script>
import test from "@/components/test/"
export default {
data () {
return {
msg: 'hello'
}
},
methods: {
getMsg (res) {
console.log(res)
}
},
components: {test}
}
</script>
Brother Components Newsletter
Use of uni-ui
uni-ui documentation
1. Enter the Grid Grid component
2、Use HBuilderX to import the component
3. Import the component
import uniGrid from "@/components/uni-grid/"
import uniGridItem from "@/components/uni-grid-item/"
4、Registered components
components: {uniGrid,uniGridItem}
5. Use of components
<uni-grid :column="3">
<uni-grid-item>
<text class="text">copies</text>
</uni-grid-item>
<uni-grid-item>
<text class="text">copies</text>
</uni-grid-item>
<uni-grid-item>
<text class="text">copies</text>
</uni-grid-item>
</uni-grid>