# Application Config

Every Vue application exposes a config object that contains the configuration settings for that application:

const app = Vue.createApp({})

app.config = {...}
App Configuration Description H5 App Terminal WeChat Mini Program Description
errorHandler Specifies a handler function to handle uncaught errors thrown during the execution of the component's render method and by the listener. Details
warnHandler Specify a custom handler for Vue's runtime warnings. Details
globalProperties Adds a global property that can be accessed in any component instance within the application. Details
isCustomElement Specifies a method to identify custom elements defined outside of Vue. Details
optionMergeStrategies Define merge strategies for custom options. Details
performance Set to true to enable performance tracking of component initialization, compilation, rendering and updates in the performance/timeline panel of the browser dev tools. Details x x Only supported in Web environment

# Application API

In Vue 3, APIs that globally mutate Vue's behavior are now moved to application instances created by the new createApp method. In addition, their effects are now scoped to that specific application's instance:

import { createApp } from 'vue'

const app = createApp({})

Calling createApp returns an application instance. This instance provides an application context. The entire component tree mounted by the application instance share the same context, which provides the configurations that were previously "global" in Vue 2.x.

In addition, since the createApp method returns the application instance itself, you can chain other methods after it which can be found in the following sections.

应用 API 描述 H5 App端 微信小程序 说明
component 注册或检索全局组件。详情
config 包含应用配置的对象。详情
directive 注册或检索全局指令。详情 x
mixin 在整个应用范围内应用混入。详情 nvue 页面暂不支持
provide 设置一个可以被注入到应用范围内所有组件中的值。详情
use 安装 Vue.js 插件。详情

# Global API

Global API Description H5 App WeChat Mini Program
createApp Returns an application instance that provides the application context. The entire component tree mounted by an application instance shares the same context. Details
h Returns a "virtual node", often abbreviated VNode: a plain object that contains information describing to Vue what kind of node it should render on the page, including descriptions of all child nodes. Details x x
defineComponent By implementation, defineComponent only returns the object passed to it. However, in terms of type, the returned value has a synthetic type constructor for manual rendering functions, TSX and IDE tool support. Details x x
defineAsyncComponent Creates an asynchronous component that is loaded only when needed. Details x x
resolveComponent Allows component to be resolved by name if available in the current application instance. Returns a Component. Details x x
resolveDynamicComponent allows to resolve a component using the same mechanism as component :is="". Details x x
resolveDirective Allows a directive to be resolved by its name if available in the current application instance. Returns a Directive. Details x x
withDirectives allows directives to be applied to a VNode. Returns a VNode containing application instructions. Details x x
createRenderer createRenderer function accepts two generic parameters: HostNode and HostElement, corresponding to the Node and Element types in the host environment. Details x x
nextTick Defer callback execution until after the next DOM update cycle. Use it immediately after changing some data to wait for DOM to update. Details x x

# Options/Data

Data Description H5 App WeChat Mini Program
data A function that returns the data object of the component instance. Details
props props can be an array or an object to receive data from the parent component. Details
computed The computed property will be mixed into the component instance. The this context of all getters and setters is automatically bound to the component instance. Details
methods methods will be mixed into the component instance. These methods can be accessed directly through the VM instance, or used in instruction expressions. this in a method is automatically bound to the component instance. Details
watch An object, the key is the expression to watch, and the value is the corresponding callback function. The value can also be a method name, or an object containing options. Details
emits emits can be an array or object to fire custom events from the component, emits can be a simple array, or an object instead, allowing configuration and event validation. Details

# Options/DOM

DOM Description H5 App WeChat Mini Program Description
template A string template to use as the identifier for the component instance. Details x x The vue used by uni-app is the version that only contains runtime
render An alternative to string templates, allowing you to take full advantage of the programming capabilities of JavaScript. Details x x -

# Options/Lifecycle hooks

Lifecycle hooks Description H5 App terminal WeChat applet
beforeCreate Called after instance initialization, before data observer and event/watcher event configuration. Details
created Called immediately after the instance is created. Details
beforeMount Called before the mount starts: the associated render function is called for the first time. Details
mounted Called after the instance is mounted, when Vue.createApp({}).mount() is replaced by the newly created vm.$el. Details
beforeUpdate Called when data is updated, before the virtual DOM is patched. Details
updated This hook is called after the virtual DOM is re-rendered and patched due to data changes. Details
activated Called when a component cached by keep-alive is activated. Details x
deactivated Called when a component cached by keep-alive is deactivated. Details x
beforeUnmount Called before the component instance is unmounted. At this stage, the instance is still completely normal. Details
unmounted Called after the component instance is unmounted. When this hook is called, all directives of the component instance are unbound, all event listeners are removed, and all child component instances are unloaded. Details
errorCaptured Called when an error from a descendant component is captured. This hook receives three parameters: the error object, the component instance where the error occurred, and a string containing information about the source of the error. Details
renderTracked Called when the tracked virtual DOM is re-rendered. The hook receives debugger event as a parameter. This event tells you which action tracked the component and the target object and key for that action. Details
renderTriggered When the virtual DOM is re-rendered to triggered.Similarly to renderTracked, receive a debugger event as a parameter. This event tells you what action triggered the re-render, and the target object and key for that action. Details

页面及组件生命周期流程图

# Options/Assets

Resources Description H5 App Terminal WeChat Mini Program
directives A hash table containing the directives available to the component instance. Details x
components Contains a hash table of components available for a component instance. Details

# Options/Composition

Combination Description H5 App Terminal WeChat Mini Program
mixins Receives an array of mixin objects. These mixins can contain instance options just like normal instance objects, and these options will be merged into the final option, using specific option merge logic. Details
extends allows a declaration to extend another component (can be a simple options object or a constructor). This is mainly to facilitate extending single-file components. Details
provide / inject The pair of options needs to be used together to allow an ancestor component to inject a dependency into all its descendants, no matter how deep the component hierarchy is, and it will always take effect as long as the upstream and downstream relationships are established. Details
setup The setup function is a new component option. It acts as an entry point for using the composition API inside the component. Details

# Options/Misc

Miscellaneous Description H5 App Terminal WeChat Mini Program
name allows the component template to call itself recursively. Note that when a component is registered globally with Vue.createApp({}).component({}), the global ID is automatically used as the component's name. Details
delimiters Sets the delimiters used for text insertion within templates. Details x x
inheritAttrs By default parent-scoped attribute bindings (attribute bindings) that are not considered props will "fall back" and be applied to the root element of child components as normal HTML attributes superior. By setting inheritAttrs to false when writing components that wrap a target element or another component, these default behaviors will be removed. Details x

# Instance Properties

Instance property Description H5 App WeChat applet Description
$data The data object observed by the component instance. A component instance proxies access to its data object property. Details
$props The props object received by the current component. A component instance proxies access to its props object property. Details
$el The root DOM element used by the component instance. Details x x
$options Init options for the current component instance. Useful when you need to include custom property in options. Details
$parent Parent instance, if the current instance has one. Details The built-in tags such as view and text on the H5 side are Vue Component implementation, $parent will get these to built-in components, the problem is that this.$parent is inconsistent with other platforms, the solution is to use this.$parent.$parent to get or customize the root node of the component Changed from view to div
$root 当前组件树的根组件实例。如果当前实例没有父实例,此实例将会是其自己。详情
$slots 用来访问被插槽分发的内容。每个具名插槽有其相应的 property (例如:v-slot:foo 中的内容将会在 this.$slots.foo 中被找到)。详情
$refs 一个对象,持有注册过 ref attribute 的所有 DOM 元素和组件实例。详情 非H5端只能用于获取自定义组件,不能用于获取内置组件实例(如:viewtext),uni-app x 内置组件绑定 ref 会返回组件根节点的引用。
$attrs Contains props or custom events that are not part of the parent scope. Details x -

# Instance Methods

Instance method Description H5 App terminal WeChat applet
$watch Listen to changes in reactive property or function evaluation results on component instances. Details
$emit Trigger an event on the current instance. Additional parameters are passed to the listener callback. Details
$forceUpdate Forces the component instance to re-render. Note that it only affects the instance itself and subcomponents that insert the contents of the slot, not all subcomponents. Details
$nextTick Delay callback execution until after the next DOM update loop. Use it immediately after modifying the data, then wait for the DOM to update. Details

# Directives

Vue Directive Description H5 App WeChat Mini Program Description
v-text Update the textContent of the element. Details x
v-html Update the innerHTML of an element. Details WeChat MiniApp will be converted into rich-text
v-show Toggles the element's display CSS property based on the true or false value of the expression. Details
v-if Conditionally render elements based on the true or false value of an expression. Details
v-else Adds "else block" for v-if or v-else-if. Details
v-else-if means the “else if block” of v-if. Can be chained. Details
v-for Renders an element or template block multiple times based on source data. Details
v-on Bind event listener. Details
v-bind Dynamically bind one or more attributes, or a component prop to an expression. Details
v-model Creates two-way bindings on form controls or components. Details
v-slot Provides a named slot or a slot that needs to receive prop. Details
v-pre Skips compilation of this element and its children. Details x
v-cloak This directive remains on the element until the associated component instance finishes compiling. Details x x
v-once Render elements and components only once. Details x
v-Yes Templates are subject to native HTML parsing rules when used within DOM templates. Details x x -

# Special Attributes

Special Properties Description H5 App WeChat Mini Program Description
key The special attribute of key is mainly used in Vue's virtual DOM algorithm to identify VNodes when comparing old and new nodes. Details
ref ref is used to register references to elements or subcomponents. Details Non-H5 platform can only get vue component instance but cannot get built-in component instance
Yes Use Dynamic Components. Details x -

# Built-In Components

Built-in components Description H5 App WeChat applet
component 渲染一个“元组件”为动态组件。依 is 的值,来决定哪个组件被渲染。 详情 x
transition Transition effect as a single element/component. Details x x
transition-group As a transition effect for multiple elements/components. Details x x
keep-alive When wrapping dynamic components, inactive component instances are cached instead of destroying them, mainly to preserve component state or avoid re-rendering. Details x x
slot Distribute slots as content in component templates. The slot element itself will be replaced. Details
teleport Move part of the template to a different location in the DOM than the Vue app. Details x x -

# Reactivity API

# Basic Reactivity APIs

Responsive Basic API Description H5 App Terminal WeChat Mini Program
reactive Returns a reactive copy of the object. Details
readonly Takes an object (reactive or plain) or ref and returns a read-only proxy for the original proxy. Details
isProxy Checks whether the object is a reactive or readonly created proxy. Details
isReactive Checks if the object is a reactive proxy created by reactive. Details
isReadonly Checks if the object is a read-only proxy created by readonly. Details
toRaw Returns the raw object of the reactive or readonly proxy. Details
markRaw Marks an object so that it will never be converted to a proxy. Return the object itself. Details
shallowReactive Creates a reactive proxy that tracks the reactivity of its own property, but does not perform deep reactive transformations of nested objects (exposing primitive values). Details
shallowReadonly Creates a proxy that makes its own property read-only, but does not perform deep read-only conversions of nested objects (exposing primitive values). Details

# Refs

Refs Description H5 App Terminal WeChat Mini Program
ref Takes an internal value and returns a reactive and mutable ref object. ref objects have a single property .value that points to the internal value. Details
unref Returns the internal value if the argument is ref, otherwise returns the argument itself. This is val = isRef(val) ? val.value : val. Details
toRef can be used to create a ref for a property property on the source reactive object. The ref can then be passed out, maintaining a reactive connection to its source property. Details
toRefs Converts a reactive object to a normal object, where each property of the resulting object is a ref pointing to the corresponding property of the original object. Details
isRef Check if the value is a ref object details
customRef Create a custom ref with explicit control over its dependency tracking and update triggering. Details
shallowRef Creates a ref that tracks its own .value changes, but does not make its value responsive. Details
triggerRef Manually execute any effects associated with shallowRef. Details

# Computed and watch

Computed and watch Description H5 App WeChat Mini Program
computed Use the getter function and return an immutable reactive ref object for the value returned from the getter. Details
watchEffect Runs a function as soon as its dependencies are tracked reactively, and re-runs it when dependencies are changed. Details
watch The watch API is exactly equivalent to the option API this.$watch (and the corresponding watch option). watch needs to listen to a specific data source and has side effects in a separate callback function. Details

# Composition API

Combined API Description H5 App Terminal WeChat Mini Program
setup A component option that is executed before the component is created, once the props are resolved, and serves as the entry point to the composite API. Details
Lifecycle Hooks Lifecycle hooks can be registered using the directly imported onX function. [Details](https://v3.cn.vuejs.org/api/composition-api.html#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9 %92%A9%E5%AD%90)
Provide / Inject provide and inject enable dependency injection. Both can only be called during setup() using the currently active instance. Details
getCurrentInstance Allows access to internal component instances useful for advanced use or library creators. Details

# Global variable

The way to implement global variables needs to follow the development specifications of Vue single file mode.

# Other configuration

Vue 组件编译到小程序平台的时候会编译为对应平台的组件,部分小程序平台支持 options 选项(具体选项参考对应小程序平台文档的自定义组件部分),一般情况默认即可,如有特殊需求可在 Vue 组件中增加 options 属性。

属性 类型 默认值 描述 平台兼容性
multipleSlots Boolean true 在组件定义时的选项中启动多slot支持
styleIsolation String apply-shared 组件样式隔离方式,具体配置选项参见:组件样式隔离 微信小程序
addGlobalClass Boolean true 这个选项等价于设置 styleIsolation: apply-shared ,但设置了 styleIsolation 选项后这个选项会失效 微信小程序
virtualHost Boolean false 将自定义节点设置成虚拟的,更加接近Vue组件的表现。我们不希望自定义组件的这个节点本身可以设置样式、响应 flex 布局等,而是希望自定义组件内部的第一层节点能够响应 flex 布局或者样式由自定义组件本身完全决定,启用后可以通过 mergeVirtualHostAttributes 合并合并组件虚拟节点外层属性 微信小程序、支付宝小程序(默认值为 true)、抖音小程序(4.02+)
export default {
  props: ['data'],
  data(){ return { } },
  options: {
    virtualHost: true
  }
}

# Common problem

# 1. How to get the data passed on the previous page

Obtained in onLoad, the parameter of onLoad is the data passed by other pages to open the current page.

# 2. How to set global data and global methods

uni-app has built-in Vuex, for use in app, please refer to hello-uniapp store/index.js .

	//store.js
	import {createStore} from 'vuex'
	const store = createStore({
		state: {...},
		mutations: {...},
		actions: {...}
	})
	export default store

	//main.js
	import App from './App'
	import {createSSRApp} from 'vue'
	import store from './store'
	export function createApp() {
		const app = createSSRApp(App)
		app.use(store)
		return {
			app
		}
	}

	//test.vue When using:
	import {mapState,mapMutations} from 'vuex'

# 3. How to catch onError of app

Since onError is not a complete life cycle, only a method of catching errors is provided, and a callback function named onError can be added to the root component of the app. as follows:

	export default {
		// Only apps have an onLaunch lifecycle
		onLaunch () {
		   // ...
		},

		// capture app error
		onError (err) {
		   console.log(err)
		}
	}

# 4. Component property settings do not take effect

When some properties are repeatedly set to the same value, they are not synchronized to the View layer. For example, every time you set the scroll-top property of a scroll-view component to 0, it only gets back to the top the first time. This is due to the props unidirectional data flow feature. When the actual value of scroll top inside the component changes, the binding properties do not change with it.

There are two solutions (take the scroll-view component as an example):

  1. Monitor the scroll event, record the value of the internal change of the component, and set the current value of the record before setting the new value
	<scroll-view scroll-y="true" :scroll-top="scrollTop" @scroll="scroll"></scroll-view>
export default {
    data() {
        return {
            scrollTop: 0,
            old: {
                scrollTop: 0
            }
        }
    },
    methods: {
        scroll: function(e) {
            this.old.scrollTop = e.detail.scrollTop
        },
        goTop: function(e) {
            this.scrollTop = this.old.scrollTop
            this.$nextTick(function() {
                this.scrollTop = 0
            });
        }
    }
}

  1. Monitor the scroll event, get the value of the internal change of the component, and update its binding value in real time
	<scroll-view scroll-y="true" :scroll-top="scrollTop" @scroll="scroll"></scroll-view>
	export default {
		data() {
			return {
				scrollTop: 0,
			}
		},
		methods: {
			scroll: function(e) {
				// If you use this method, please add debounce by yourself
				this.scrollTop = e.detail.scrollTop
			},
			goTop: function(e) {
				this.scrollTop = 0
			}
		}
	}

The second solution may cause jitter in some components, and the first solution is recommended .