Vue3 API
Application API
- directive
Global API
- createApp
- h
- defineComponent
- defineAsyncComponent
- resolveComponent
- resolveDynamicComponent
- resolveDirective
- withDirectives
- createRenderer
- nextTick
Reactivity API
- ref
- unref
- toRef
Application API
directive
參數:
- name
- 自定義選項 definition(optional)
返回值:
如果傳入了自定義參數,則為應用程序實例
如果沒有傳入自定義參數,則自定義指令
用法:
注冊或檢索一個全局指令
import { createApp } from 'vue' const app = createApp({}) app.directive('my-direcive', { beforeMount() {}, mounted() {}, beforeUpdate() {}, updated() {}, beforeUnmount() {}, beforeUnmount() {}, unmounted() {} }) app.directive('my-directive', () => { }) const myDirective = app.directive('my-directive')
指令鈎子會傳遞這些參數:
el
指令綁定的元素。它可以用來操作DOM
binding
一個包含以下屬性的對象:
- instance 使用了指令的組件實例
- value 傳入指令的值,如:v-my-directive="1 + 1", value是2
- oldValue 前值
- arg 傳入指令的參數,如 v-my-directive:foo, arg參數是foo
- modifiers 一個包含修飾符的對象,如:v-my-directive.foo.bar,修飾符對象就是 {foo: true, bar: true}
- dir 一個對象,當指令被注冊后傳入一個參數
app.directive('focus', {
mounted(el) {
el.focus()
}
})
dir就是下面這個對象:
{
mounted(el) {
el.focus()
}
}
vnode
作為el參數接收的實際DOM元素的藍圖
prevNode
上一個虛擬節點
provide
參數:
- {string | Symbol} key
- value
返回值:應用實例
用法:
設置一個可以注入到應用程序中的所有組件中的值。組件應該使用inject來接收提供的值。
從provide/inject的角度來看,應用程序可以被認為是根級別的祖先,根組件是它唯一的子組件。
不應該將此方法與復合API中的提供組件選項或提供函數混淆,雖然這些也是相同的provide/inject機制的一部分,但它們用於配置組件(而不是應用程序)提供的值.
在編寫插件時,通過應用程序提供值特別有用,因為插件通常不能使用組件提供值。它是全局屬性的另一種選擇。
provide和inject綁定不是反應性的。這是故意的,但是,如果您向下傳遞一個被觀察的對象,該對象上的屬性將保持響應性。
示例:
注入一個屬性到根組件
import { createApp } from 'vue' const app = createApp({ inject: ['user'], template: ` <div>{{ user }}</div> ` }) app.provide('user', 'administrator')
unmount
參數:
- {Element | string} rootContainer
在所提供的DOM元素上卸載應用程序實例的根組件
<body> <div id="my-app"></div> </body>
import { createApp } from 'vue' const app = createApp({}) app.mount('#my-app') setTimeout(() => app.unmount('#my-app'), 5000)
use
參數:
- {Object | Function} plugin
- ...options(optional)
返回值:應用實例
用法:
安裝一個vue.js的插件。如果插件是一個對象,它必須公開一個安裝方法。如果它本身是一個函數,它將被視為安裝方法。
安裝方法將以應用程序作為其第一個參數調用。傳遞給使用的任何選項都將在后續參數中傳遞。
當對同一個插件多次調用此方法時,該插件將只安裝一次。
Global API
createApp
返回一個應用實例
const app = Vue.createApp({})
你可以在createApp后面鏈式調用其他方法
參數:
該方法接受一個根組件選項對象作為第一個參數
const app = Vue.createApp({ data() { return { ... } }, methods: {...}, computed: {...} ... })
第二個參數:可傳入根組件props到應用
js
const app = Vue.createApp( { props: ['username'] }, { username: 'Evan' } )
html
<div id="app">
<!-- 將顯示 Evan -->
{{ username }}
</div>
Typing(類型)
interface Data { [key: string]: unknown } export type CreateAppFunction<HostElement> = ( rootComponent: PublicAPIComponent, rootProps?: Data | null ) => App<HostElement>
h
返回“虛擬節點”,VNode,一個簡單的對象,它包含描述Vue應該在頁面上呈現何種類型的節點的信息,包括對任何子節點的描述。它用於手工編寫的render函數
render() { return Vue.h('h1', {}, 'Some title') }
參數:
- type(必選)
類型:String | Object | Function
描述:一個HTML標簽名、一個組件或一個異步組件
- props(可選)
類型:Object
描述:模板中使用的屬性、props和事件的對象
- children(可選)
類型:String | Array | Object
描述:子節點,使用h()構建,或使用字符串來獲取“純文本節點”,或帶有slot插槽的對象
h('div', {}, [ 'Some text comes first', h('h1', 'A headline'), h(MyComponent, { someProp: 'foobar' }) ])
defineComponent
在實現方面,defineComponent只返回傳遞給它的對象。但是,就類型而言,返回值具有人工呈現函數的構造函數的合成類型、TSX和IDE工具的支持
參數:
- 一個帶有組件選項的對象
import { defineComponent } from 'vue' const MyComponent = defineComponent({ data() { return { count: 1 } }, methods: { increment() { this.count++ } } })
- 或者是一個setup函數,函數名將會被當做組件名
import { defineComponent, ref } from 'vue' const HelloWorld = defineComponent(function HelloWorld() { const count = ref(0) return { count } })
defineAsyncComponent
創建一個異步組件,只在需要的時候加載
參數:
對於基本用法,defineAsyncComponent可以接受返回promise的工廠函數。當你從服務器檢索到組件定義時,應該調用Promise的解析回調。你還可以調用reject(reason)來指示負載已經失敗。
import { defineAsyncComponent } from 'vue' const AsyncComp = defineAsyncComponent(() => import('./components/AsyncComponent.vue')) app.component('async-component', AsyncComp)
當使用本地注冊,你也可以直接提供一個函數,返回一個promise
import { createApp, defineAsyncComponent } from 'vue' createApp({ components: { AsyncComponent: defineAsyncComponent(() => import('./components/AsyncComponent.vue')) } })
對於高級用法,defineAsyncComponent可以接受一個對象。
defineAsyncComponent方法也可以返回一個以下格式的對象:
import { createApp, defineAsyncComponent } from 'vue' createApp({ components: { AsyncComponent: defineAsyncComponent(() => import('./components/AsyncComponent.vue')) } }) import { defineAsyncComponent } from 'vue' const AsyncComp = defineAsyncComponent({ loader: () => import('./Foo.vue'), loadingComponent: LoadingComponent, errorComponent: ErrorComponent, delay: 200, timeout: 3000, suspensible: false, onError(error, retry, fail, attempts) { if (error.message.match(/fetch/) && attempts <= 3) { // retry on fetch errors, 3 max attempts retry() } else { fail() } } })
resolveComponent
提示:resolveComponent 僅用於render和setup
如果組件在當前應用程序實例中可用,則允許按其名稱解析組件
const app = Vue.createApp({}) app.component('MyComponent', { }) import { resolveComponent } from 'vue' render() { const MyComponent = resolveComponent('MyComponent') }
參數:
- name
類型: String
描述: 一個被加載的組件的名稱
resolveDynamicComponent
提示:resolveDynamicComponent 僅用於render和setup
允許和<component :is="">相同的機制來解析一個組件
返回解析的組件或以組件名稱作為節點標記的新創建的VNode.如果未找到該組件,將發出警告。
import { resolveDynamicComponent } from 'vue' render() { const MyComponent = resolveDynamicComponent('MyComponent') }
參數:
- component
類型:String | Object(組件選項對象)
描述:-
resolveDirective
提示:resolveDirective僅可用於render和setup
允許根據一個directive的名稱來解析,只要這個directive可被用於應用實例中。返回一個Directive,如果沒有找到則返回undefined
const app = Vue.createApp({}) app.directive('highlight', {}) import { resolveDirective } from 'vue' render() { const highlightDirective = resolveDirective('highlight') }
參數:
- name
類型:String
描述:一個已加載的指令的名稱
withDirectives
提示:withDirectives只能被用於render和setup
允許對一個VNode應用指令,返回一個已應用指令的VNode
import { withDirectives, resolveDirective } from 'vue' const foo = resolveDirective('foo') const bar = resolveDirective('bar') return withDirectives(h('div'), [ [foo, this.x], [bar, this.y] ])
參數:
- vnode
類型:vnode
描述:一個虛擬節點,通常由h()創建
- directives
類型:Array
描述:指令的數組
每個指令自身是一個數組,該數組允許4個成員
[directive, value, arg, modifiers]
- directive: 指令自身,必選
const MyDirective = resolveDirective('MyDirective')
const nodeWithDirectives = withDirectives(h('div'), [[MyDirective]])
- value: 賦值給指令的值(類型:any)
const MyDirective = resolveDirective('MyDirective')
const nodeWithDirectives = withDirectives(h('div'), [[MyDirective, 100]])
- arg:一個String參數
const MyDirective = resolveDirective('MyDirective');
const nodeWithDirectives = withDirectives(h('div'), [[MyDirective, 100, 'click']])
- modifiers:修飾符,一個 key: value 鍵值對對象
createRenderer
createRenderer函數接受兩個通用參數:HostNode和HostElement,它們對應於主機環境中的節點和元素類型
例如,對於運行時-DOM,HostNode是DOM節點接口,而HostElement是DOM元素接口
自定義渲染器可以像這樣傳入平台特定類型:
import { createRenderer } from 'vue' const { render, createApp } = createRenderer<Node, Element>({ patchProp, ...nodeOps })
參數:
- HostNode
類型:Node
描述:host環境下的node
- HostElement
類型:Element
描述:host環境下的element
nextTick
將回調延遲到下一個DOM更新周期之后執行。在更改了一些數據以等待DOM更新之后立即使用它。
import { createApp, nextTick } from 'vue' const app = createApp({ setup() { const message = ref('Hello!') const changeMessage = async newMessage => { message.value = newMessage await nextTick() console.log('Now DOM is updated') } } })
ref
獲取一個內部值並且返回一個reactive、可變的ref對象。ref對象有一個指向內部值的屬性value
示例
const count = ref(0) console.log(count.value); // 0 count.value++ console.log(count.value); // 1
如果一個對象被賦值為ref的值,那么這個對象將通過reactive方法變得非常具有活性。
Typing
interface Ref<T> { value: T } function ref<T>(value: T): Ref<T>
有時,我們可能需要為ref的內部值指定復雜類型。我們可以通過在調用ref覆蓋默認推斷時傳遞一個泛型參數來簡潔地做到這一點,例如:
const foo = ref<string | number>('foo') foo.value = 123 // ok
如果泛型的類型未知,建議將ref轉為Ref<T>
function useState<State extends string>(initial: State) { const state = ref(initial) as Ref<State> return state }
unref
如果參數是ref,則返回內部值,否則返回參數本身,這是一個糖函數,val = isRef(val) ? val.value : val;
function useFoo(x: number | Ref<number>) { const unwrapped = unref(x) }
參考文檔:https://v3.vuejs.org/api/global-api.html#createapp
推薦: 一文看懂Vue3.0的優化
https://lightproxy.org/zh-CN
一個 Web 調試代理工具,大家可以了解一下