Vue3 API

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 调试代理工具,大家可以了解一下

posted on 2020-10-14 17:38  白小鸽  阅读(933)  评论(0编辑  收藏  举报