# Introductory tutorial for component usage

  • Component is the basic unit of the view layer.
  • Component is the encapsulation of a single and reusable functional module.

Each component includes the following parts: start tag and end tag marked by component name, component content, component attribute and component attribute value.

  • The component name is wrapped in angle brackets, called tag, which has a start tag and an end tag. Use / after < of the end tag to indicate the end. An end tag is also called a closing tag. For example, in the following example, <component-name> is the start tag, and </component-name> is the end tag.
  • The content between the start tag and the end tag is called component content. For example, content in the example below
  • Attributes can be written on the start tag, and there can be multiple attributes, which are separated by spaces. For example, property1 and property2 in the following example. Note that attributes cannot be written on closing tags.
  • Each attribute is assigned a value by =. As in the example below, the value of the attribute property1 is set to the string value.

Note: All component and attribute names are lowercase, with hyphens between words connected by a hyphen -.

<component-name property1="value" property2="value">
	content
</component-name>

The following is an example of a basic component. Insert an <button> component under the root <view> component of a vue page. Write the text "button" in the content area of this component, and set an attribute "size" for this component, and the attribute value of "size" is set to "mini".

Note: According to vue single file component specification, the root node of each vue file must be <template>, and there must be only one root <view> component under this <template>.

<template>
	<view>
		<button size="mini">按钮</button>
	</view>
</template>

By understanding the documentation of button component, we can see that the above code will draw a button on the page, the text displayed on the button is "button", and the size of the button is small.

# Attribute type of components

There are many types of attributes of components:

Type Describe Annotation
Boolean Boolean value The attribute is written on the component, no matter what the attribute is equal to, its value is true. Only when the attribute is not written on the component, the attribute value is false. If the attribute value is a variable, the value of the variable will be converted to the Boolean type.
Number Digit 1, 2.5
String String "string"
Array Array [ 1, "string" ]
Object Object { key: value }
EventHandler Event handler function name handlerName is the name of the event handling function defined in methods
Any Arbitrary attribute

The following example shows an example of setting boolean values and numbers to properties of a component. Note that false is used as a js variable. When using it in the properties of a component, the property needs to be prefixed with a : colon. The property value is still wrapped in quotation marks, but the quotation marks are not strings, but js.

<template>
	<view>
		<button size="mini" :disabled="false" hover-start-time=20 >按钮</button>
	</view>
</template>

# Public attribute list

Each component has its own defined attributes, but all components of uni-app have the following attributes:

Attribute name Type Describe Annotation
id String Unique identifier for components It is generally used to obtain the component context object (such as: VideoContext), and the entire page needs to be unique
ref String Unique identifier of components in vue It is used to register reference information for sub-components, see Vue documentation for details
class String Style class of components Style class defined in the corresponding css
style String Inline styles of components Inline style that can be set dynamically
hidden Boolean Whether components are hidden? All components are displayed by default
data-* Any Custom attributes When event is triggered on component, it will be sent to the event handler.
@* EventHandler Events of components For details, please refer to the detailed documentation of each component. For event binding, refer to [Event Handler](/tutorial/vue-basics?id=%E4%BA%8B%E4%BB%B6% E5%A4%84%E7%90%86%E5%99%A8)

In addition to the above public properties, there is also a special class of properties starting with v-, called vue directives, such as v-if, v-else, v-for, v-model. For details, see vue command

# Use js variables in components

js variables defined in the data of script can be used in the component, but the usage in the attributes of the component is different from that in the content area.

  • When used in the content area, use two curly braces to wrap, such as the following buttonText
  • When used in attribute values, the attribute name should be prefixed with a colon.

The following examples of button component are equivalent to the previous examples. Only that the static content is changed to dynamic js.

<template>
	<view>
		<button size="mini" :disabled="buttondisble" hover-start-time=20 >{{buttonText}}</button>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				"buttonText":"按钮",
				"buttondisble":false
			}
		}
	}
</script>

# Component events

Each component has an "event". Event is to trigger a js method under specified conditions.

For example, if button component has a click event, that means when the mobile phone user clicks the button component, this event will be triggered.

Events are also attributes of components, but such attributes are prefixed with @.

The attribute value of the event points to a js method defined in the methods of script, and you can also pass parameters to the method.

The following are examples of component events:

  • click is the click event of the button component, which is triggered when the user clicks the button
  • click points to the goto method defined in methods and passes the parameter '/pages/about/about'
<template>
	<view>
		<button size="mini" @click="goto('/pages/about/about')">按钮</button>
	</view>
</template>
<script>
    export default {
        methods: {
            goto(url) {
                console.log("按钮被点击了,且传入的参数是:" + url)
            }
        }
    }
</script>

# Basic component

uni-app components are divided into basic components and extended components.

The basic components have been built in the uni-app framework. There is no need to import the files of the built-in components into the project or register the built-in components, which can be used directly at any time, such as the <view> component.

All components other than the basic components are called extended components. The extended components can be used only after they are imported into the project.

uni-app provides developers with a series of basic components, similar to the basic tag elements in HTML.

However, the components of uni-app are different from HTML, but are the same as small programs, which can better meet the usage habits of mobile phones.

Although HTML tags are not recommended, in fact, if developers write tags such as div, they will be converted to view tags by the compiler when they are compiled to a non-H5 platform. Similarly, span is converted to text, A is converted to navigator, etc., including the element selector in css. However, for the sake of convenient management and unified policies, it is still recommended to use components such as view when writing new code.

Developers can combine these basic components for quick development. It can be encapsulated as an extended component if reuse is needed.

uni-app The basic component specification, which is similar to the applet specification. If you understand applet development, the basic components of uni-app will feel familiar. But you need to pay attention to the event binding on the component, which needs to be bound with vue's event binding syntax, such as bindchange="eventName" event, which needs to be written as @change="eventName"

	<picker mode="date" :value="date" start="2015-09-01" end="2020-09-01" @change="bindDateChange">
		<view class="picker">
		  当前选择: {{date}}
		</view>
	</picker>

# List of basic components

Basic components are divided into the following ten categories:

View Container:

Component name Instruction
view View container, similar to div in HTML
scroll-view scrollable view container
swiper Slider view container, such as for carousel banner
match-media Dynamic screen adaptation component, such as some content not displayed on narrow screen
movable-area Dragable area
movable-view A movable view container that can be dragged, swiped or pinch-zoomed on the page. movable-view must be in movable-area component
cover-view A text component that can be covered on the native component
cover-image An image component that can be covered on the native component

Basic Content:

Component name Instruction
icon icon
text characters
rich-text Rich Text Display Component
progress Progress bar

Form:

Label name Instruction
button Button
checkbox Multiple selectors
editor Rich text input box
form form
input Input Box
label label
picker Popup Picker
picker-view Form inline list selector
radio Single selector
slider Slide selector
switch Switch selector
textarea Multi-line text input box

Routing and Page Navigation:

Component name Instruction
navigator page link. Similar to the a tag in HTML

Media:

Component name Instruction
audio Audio
camera Camera
image Image
video Video
live-player Live playback
live-pusher Real-time audio and video recording, also known as live streaming

Map:

Component name Instruction
map map

Canvas:

Component name Instruction
canvas Canvas

webview(Web-view):

Component name Instruction
web-view web browser component

Advertisement

Component name Instruction
ad Ad Component
ad-draw Immersive Video Streaming Ad Component

Page attribute configuration

Component name Instruction
custom-tab-bar Bottom tabbar custom component
navigation-bar Top Navigation
page-meta Page property configuration node

uniCloud

Component name Instruction
unicloud-db component uniCloud database access and manipulation component

Specific components for each platform

On the applet platform and nvue platform, there are also some proprietary components, such as open-data, see the left navigation for details

# Meaning of extending components

Although all business requirements can be met by basic components, but basic components alone are inefficient, and there will be many encapsulated components in actual development.

For example, if we need a pentagram click rating component, it is available in the DCloud plug-in market: https://ext.dcloud.net.cn/plugin?id=33

Import this uni-rate component into your uni-app project, refer to it in the required vue page, and you can display this five-pointed star component in the specified place.

	<!-- Refer the uni-rate component on the index.vue page -->
	<template>
		<view>
			<uni-rate></uni-rate><!-- 这里会显示一个五角星,并且点击后会自动亮星 -->
		</view>
	</template>

Advantages of encapsulated extended components:

  • Components can be reused arbitrarily.
  • Reasonable division of components is helpful to improve the application performance.
  • The code is more convenient for organization and management, and has stronger expansibility, which is convenient for collaborative development by many people.
  • Component-based development can greatly improve the efficiency, testability and reusability of application development.

# Component categories

The components supported by uni-app are divided into vue components and small program custom components.

If you don't know about these two components, you can refer to their respective documentation

  • vue components: documentation
  • Miniprogram custom component: its specification is not the vue specification, but the miniprogram specification, [document](https://uniapp.dcloud.net.cn/tutorial/miniprogram-subject.html#%E5%B0%8F% E7%A8%8B%E5%BA%8F%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BB%84%E4%BB%B6%E6%94%AF%E6% 8C%81)

For daily development, it is recommended to use vue components. uni-app supports applet components mainly to be compatible with more ecological resources.

If the extension component conforms to the easycom component specification of uni-app, it can be used directly without registration. For example, the uni-ui extension component conforms to the easycom component specification.

For the components not conforming to the easycom specification, you need to manually import and register these components in the code before implementation.

Besides easycom specification, there are many concepts of extension components, such asuni_module, datacom, Native component, uniCloud component.

Let us explain them one by one.

# easycom component specification

Supported in HBuilderX 2.5.5+

Traditional vue components need to be installed, referenced and registered before they can be used.easycom Streamline it to one step.

As long as the components are installed in the components directory of the project oruni_modules directory, and conform to components/ component name/ component name.vue directory structure. You can use it directly in the page without reference or registration.

For example, the uni-rate component in the previous example, after it is imported into the uni-app project, it is stored in the directory /components/uni-rate/uni-rate.vue

At the same time, its component is also called uni-rate, so that such a component does not need to be registered and referenced in script. As follows:

<template>
		<view>
			<uni-rate></uni-rate><!-- 这里会显示一个五角星,并且点击后会自动亮星 -->
		</view>
	</template>
<script>
	//There is no need to introduce by import or register uni-list components in components. You can use it directly in template
	export default {
		data() {
			return {
				
			}
		}
	}
</script>

No matter how many components are installed in the components directory, easycom will automatically remove unused components after packaging, which is particularly friendly to the use of component library.

The component library is installed in batches, and it can be used at will, and automatically packed on demand. Take the official uni-ui as an example, select the uni-ui project template in the HBuilderX new project interface, just knock u in the page to pull out a large number of component code blocks, and select directly to use. Greatly improve the development efficiency and lower the use threshold.

The components that conform to the directory structure of components/ component name/ component name.vue downloaded in the DCloud plug-in market can be used directly.

easycom is automatically turned on instead of manually.

If your component name or path does not comply with easycom's default specification, you can personalize it in the easycom node of pages.json to customize the matching component strategy. See also

If you do not use easycom to manually reference and register vue components, you need to write the following code in 3 steps:

  1. Import components in import
  2. Registering components in components
  3. Use components in template
	<template>
		<view>
			<uni-rate text="1"></uni-rate><!-- 3.使用组件 -->
		</view>
	</template>
	<script>
		import uniRate from '@/components/uni-rate/uni-rate.vue';//1.导入组件
		export default {
			components:{uniRate }//2.注册组件
		}
	</script>

# uni_module specification

uni_module actually serves more than components, it can serve components, js libraries, pages, projects and other categories supported by the DCloud plug-in market.

Components that meet the uni_module specification are stored in the uni_modules directory of the project, with the plug-in id as the directory. (The project template is not placed in the uni_modules directory)

Right-clicking in HBuilderX can conveniently update plug-ins, and plug-in authors can also conveniently upload the plug-ins.

uni_module also supports plug-ins for cloud integration.

uni_module has detailed special documents, please refer to uni_module specification.

# uniCloud component

uniCloud is a cloud development service provided by DCloud and used with uni-app.

Among the basic components of uni-app, there is a special basic component: <unicloud-db> component.

It can directly acquire and operate the cloud database of uniCloud at the front end.

For related documents, see: unicloud-db component

In addition to the built-in database components, there are uniCloud file selection and upload components in the uni-ui extension library, refer to: uni-file-picker

# Native components and native plug-ins

# Native components from basic components

There are a number of native components from the basic components of uni-app, such as video and map ...

If these components are used in vue pages for webview rendering, it will obtain a hierarchy higher than that of ordinary front-end components.

Their hierarchies can only be coved with some special components like cover-view and more considerations are required to use them.

There is no such problem in app-nvue.

For related documents, please see: uni-app built-in native component description

# The App-side native plug-in of uni-app

The App side of uni-app supports the native plug-ins, which are written in the native language of iOS or Android and encapsulated into plug-ins for other developers to call with js.

Native plug-ins can be divided into native components and native modules.

Actually, the native component can only be used in the App-nvue environment.

For related documents, please see: uni-app native plug-in development

# datacom

datacom component is a data-driven, cloud-integrated component.

Traditional components only involve the front-end concept, while datacom pulls through uniCloud cloud data, which is an essential efficiency tool for the collaborative development of uni-app+uniCloud.

For related documents, please see: datacom component

# How to encapsulate components

Encapsulating components involves a lot of knowledge, and related documents can be found in: Detailed explanation of vue component

# Expanded component (uni-ui)

See: uni-ui introduction

More components

In addition to basic components and uni-ui, there are more extension components and templates in the plug-in market, including front-end components and native extension components. For details, see Plug-in market.

For questions about whether other vue web component libraries and applet component libraries can be used in uni-app, please refer to [https://ask.dcloud.net.cn/article/35489](https://ask.dcloud. net.cn/article/35489)