vue learning notes 5: Global API of vue systematic learning notes

Posted by Evanthes on Sat, 19 Feb 2022 03:16:36 +0100

Reference documents: https://v3.cn.vuejs.org/api/global-api.html#createapp

If you are using a CDN build, the global API can be accessed through the global object Vue, for example:

const { createApp, h, nextTick } = Vue

If you use ES modules, they can be imported directly:

import { createApp, h, nextTick } from 'vue'

Global functions that handle responsiveness, such as , reactive , and , ref, are documented separately. For these functions, see Responsiveness API.

createApp:

API documentation:

Returns an application instance that provides an application context. The entire component tree mounted by an application instance shares the same context.

const app = createApp({})

You can chain call other methods after "createApp". These methods can be Application API Found in.

# parameter

This function takes a root component option object as the first parameter:

const app = createApp({
  data() {
    return {
      ...
    }
  },
  methods: {...},
  computed: {...}
  ...
})

Using the second parameter, we can pass the root prop to the application:

const app = createApp(
  {
    props: ['username']
  },
  { username: 'Evan' }
)
<div id="app">
  <!-- Will show 'Evan' -->
  {{ username }}
</div>

Root props are primitive props, like those that pass through h VNode created. In addition to the component prop, they also contain attributes and event listeners that apply to the root component.

# Type declaration

interface Data {
  [key: string]: unknown
}

export type CreateAppFunction<HostElement> = (
  rootComponent: PublicAPIComponent,
  rootProps?: Data | null
) => App<HostElement>

h:

API documentation:

Returns a "virtual node", usually abbreviated as VNode: a common object that contains information describing to Vue which node it should render on the page, including the description of all child nodes. It is intended for manual writing Rendering function:

render() {
  return h('h1', {}, 'Some title')
}

# parameter

Receive three parameters: type, props # and # children

#type

  • Type: String | Object | Function

  • Details:

    HTML tag name, component, asynchronous component or functional component. A comment is rendered using a function that returns null. This parameter is required.

#props

  • Type: Object

  • Details:

    An object that corresponds to the attribute s, prop s, and events we will use in the template. Optional.

#children

  • Type: String | Array | Object

  • Details:

    The descendant VNode is generated using {h(), or a string is used to obtain the "text VNode", or an object with a slot. Optional.

    h('div', {}, [
      'Some text comes first.',
      h('h1', 'A headline'),
      h(MyComponent, {
        someProp: 'foobar'
      })
    ])

defineComponent:

API documentation:

In terms of implementation, defineComponent {only returns the objects passed to it. However, in terms of type, the returned value has a constructor of composite type for manual rendering function, TSX and IDE tool support.

# parameter

Objects with component options

import { defineComponent } from 'vue'

const MyComponent = defineComponent({
  data() {
    return { count: 1 }
  },
  methods: {
    increment() {
      this.count++
    }
  }
})

Or a {setup} function, and the function name will be used as the component name

import { defineComponent, ref } from 'vue'

const HelloWorld = defineComponent(function HelloWorld() {
  const count = ref(0)
  return { count }
})

defineAsyncComponent:

API documentation:

Create an asynchronous component that will only be loaded when needed.

# parameter

For basic usage, defineAsyncComponent , can accept a factory function that returns , Promise ,. The # resolve # callback of Promise should be called after the server returns the component definition. You can also call {reject(reason) to indicate that the load failed.

import { defineAsyncComponent } from 'vue'

const AsyncComp = defineAsyncComponent(() =>
  import('./components/AsyncComponent.vue')
)

app.component('async-component', AsyncComp)

When used Local registration You can also directly provide a function that returns # Promise #:

import { createApp, defineAsyncComponent } from 'vue'

createApp({
  // ...
  components: {
    AsyncComponent: defineAsyncComponent(() =>
      import('./components/AsyncComponent.vue')
    )
  }
})

For higher-level usage, defineAsyncComponent can accept an object in the following format:

import { defineAsyncComponent } from 'vue'

const AsyncComp = defineAsyncComponent({
  // Factory function
  loader: () => import('./Foo.vue'),
  // Components to use when loading asynchronous components
  loadingComponent: LoadingComponent,
  // Components to use when loading fails
  errorComponent: ErrorComponent,
  // Delay before displaying loadingComponent | default value: 200 (unit: ms)
  delay: 200,
  // If timeout is provided and the time to load the component exceeds the set value, an error component will be displayed
  // Default value: Infinity (i.e. never timeout, unit: ms)
  timeout: 3000,
  // Defines whether a component can be suspended. Default value: true
  suspensible: false,
  /**
   *
   * @param {*} error Error message object
   * @param {*} retry A function that indicates whether the loader should retry when the promise loader reject s
   * @param {*} fail  A function that instructs the loader to end and exit
   * @param {*} attempts Maximum number of retries allowed
   */
  onError(error, retry, fail, attempts) {
    if (error.message.match(/fetch/) && attempts <= 3) {
      // Try again when the request has an error. You can try up to 3 times
      retry()
    } else {
      // Note that retry/fail is like resolve/reject in promise:
      // One of them must be called to continue error handling.
      fail()
    }
  }
})

defineCustomElement:

API documentation:

The method accepts and defineComponent Same parameter, but returns a native Custom element , this element can be used for any framework or not based on the framework.

Usage example:

<my-vue-element></my-vue-element>
import { defineCustomElement } from 'vue'
const MyVueElement = defineCustomElement({
  // Here are the common Vue component options
  props: {},
  emits: {},
  template: `...`,
  // For defineCustomElement only: CSS injected into shadow root
  styles: [`/* inlined css */`]
})
// Register the custom element.
// After registration, all ` < My Vue element > 'tags on the page will be upgraded.
customElements.define('my-vue-element', MyVueElement)
// You can also initialize this element programmatically:
// (this can only be done after registration)
document.body.appendChild(
  new MyVueElement({
    // Initialized prop (optional)
  })
)

resolveComponent:

API documentation:

WARNING

resolveComponent , can only be used in , render , or , setup , functions.

If it is available in the current application instance, it is allowed to resolve the} component by name.

Returns a Component. If not found, the received parameter {name is returned.

const app = createApp({})
app.component('MyComponent', {
  /* ... */
})
import { resolveComponent } from 'vue'
render() {
  const MyComponent = resolveComponent('MyComponent')
}

# parameter

Accept a parameter: name

#name

  • Type: String

  • Details:

    The name of the loaded component.

resolveDynamicComponent:

API documentation:

WARNING

resolveDynamicComponent , can only be used in , render , or , setup , functions.

It is allowed to use the same mechanism as < component: is = "" > to resolve a component.

Returns the resolved Component or newly created VNode, where the Component name is used as the node label. If the Component is not found, a warning is issued.

import { resolveDynamicComponent } from 'vue'
render () {
  const MyComponent = resolveDynamicComponent('MyComponent')
}

# parameter

Accept a parameter: component

#component

  • Type: String | Object (option object of component)

  • Details:

    For more information, see Dynamic component Documents on.

resolveDirective:

API documentation:

WARNING

resolveDirective can only be used in the 'render' or 'setup' functions.

If it is available in the current application instance, it is allowed to resolve a} directive through its name.

Returns a} Directive. If it is not found, it returns "undefined".

const app = createApp({})
app.directive('highlight', {})
import { resolveDirective } from 'vue'
render () {
  const highlightDirective = resolveDirective('highlight')
}

# parameter

Accept a parameter: name

#name

  • Type: String

  • Details:

    The name of the loaded instruction.

withDirectives:

API documentation:

WARNING

withDirectives , can only be used in the , render , or , setup , functions.

Allows instructions to be applied to VNode. Returns a VNode containing application instructions.

import { withDirectives, resolveDirective } from 'vue'
const foo = resolveDirective('foo')
const bar = resolveDirective('bar')

return withDirectives(h('div'), [
  [foo, this.x],
  [bar, this.y]
])

# parameter

Accept two parameters: vnode # and # directives.

#vnode

  • Type: vnode

  • Details:

    A virtual node, usually created using {h().

#directives

  • Type: Array

  • Details:

    An array of instructions.

    Each instruction itself is an array, and up to four indexes can be defined, as shown in the following example.

    • [directive] - the instruction itself. Required.
    const MyDirective = resolveDirective('MyDirective')
    const nodeWithDirectives = withDirectives(h('div'), [[MyDirective]])
    
    • [directive, value] - the above, plus the value assigned to the instruction of type , any.
    const MyDirective = resolveDirective('MyDirective')
    const nodeWithDirectives = withDirectives(h('div'), [[MyDirective, 100]])
    
    • [directive, value, arg] - the above, plus a string parameter, for example: click in "v-on:click".
    const MyDirective = resolveDirective('MyDirective')
    const nodeWithDirectives = withDirectives(h('div'), [
      [MyDirective, 100, 'click']
    ])
    
    • [directive, value, arg, modifiers] - the above, plus the key: value , key value pair , Object that defines any modifier.
    const MyDirective = resolveDirective('MyDirective')
    const nodeWithDirectives = withDirectives(h('div'), [
      [MyDirective, 100, 'click', { prevent: true }]
    ])

createRenderer:

API documentation:

The createRenderer function accepts two generic parameters: HostNode and HostElement, which correspond to the Node and Element types in the host environment.

For example, for runtime DOM, HostNode will be the DOM # Node interface and HostElement will be the DOM # Element # interface.

A custom renderer can pass in platform specific types as follows:

import { createRenderer } from 'vue'
const { render, createApp } = createRenderer<Node, Element>({
  patchProp,
  ...nodeOps
})

# parameter

Accept two parameters: HostNode and HostElement.

#HostNode

  • Type: Node

  • Details:

    Nodes in the hosting environment.

#HostElement

  • Type: Element

  • Details:

    Elements in the host environment.

nextTick:

API documentation:

Postpone the callback until after the next DOM update cycle. Use the DOM immediately after you change some data to wait for it to update.

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')
    }
  }
})

mergeProps:

API documentation:

Merge multiple objects containing VNode prop into a single object. It returns a newly created object, and the object passed as a parameter will not be modified.

An unlimited number of objects can be passed, and the property of the following parameters takes precedence. Event listeners are specially handled, as are class and style. The values of these properties are merged rather than overwritten.

import { h, mergeProps } from 'vue'
export default {
  inheritAttrs: false,
  render() {
    const props = mergeProps(
      {
        // This class will be merged with other classes in $attrs.
        class: 'active'
      },
      this.$attrs
    )

    return h('div', props)
  }
}

useCssModule:

API documentation:

WARNING

useCssModule , can only be used in , render , or , setup , functions.

Allow in setup Yes Single file component Function to access the CSS module.

<script>
import { h, useCssModule } from 'vue'
export default {
  setup() {
    const style = useCssModule()
    return () =>
      h(
        'div',
        {
          class: style.success
        },
        'Task complete!'
      )
  }
}
</script>
<style module>
.success {
  color: #090;
}
</style>

For more information about using CSS modules, see Single file component style features: < style module >.

# parameter

Accept a parameter: name

# noun

  • Type: String

  • Details:

    The name of the CSS module. The default is' $style '.

version:

API documentation:

Provide the version number of the installed Vue as a string.

const version = Number(Vue.version.split('.')[0])
if (version === 3) {
  // Vue 3
} else if (version === 2) {
  // Vue 2
} else {
  // Unsupported version of Vue
}

Topics: Vue Vue.js