Home  >  Article  >  Web Front-end  >  How to use Vue3 general API function

How to use Vue3 general API function

王林
王林forward
2023-05-14 22:31:041122browse

General API

version (exposes the currently used Vue version)

import Vue from 'vue';
export default {
    setup(props, context) {
        console.log(Vue.version);
        return {};
    }
};

nextTick (triggered after the Dom update is completed, used to obtain the updated Dom)

When we change the responsive state, the VueupdateDOM is not updated synchronously in real time, but all state updates executed synchronously are cached and the synchronous code is After the execution is completed, perform the Dom update operation, which greatly optimizes render performance and reduces the number of Dom updates;

And this feature brings One problem is that we cannot get the real Dom after state is changed, so Vue provides nextTick to get the updated state Dom

function nextTick(callback?: () => void): Promise<void>

Use case

<template>
    <div class="test_demo">
        <h3 class="text">{{ text }}</h3>
        <button @click="onBtnClick">更新</button>
    </div>
</template>
<script lang="ts" setup>
import { ref, nextTick } from &#39;vue&#39;;
const text = ref(&#39;test_0&#39;);
const onBtnClick = () => {
    text.value = &#39;test_1&#39;;
    nextTick(() => {
        const text = (
            document.querySelector<HTMLElement>(&#39;.text&#39;) as HTMLElement
        ).innerText;
        console.log(text);
    });
    text.value = &#39;test_2&#39;;
};
</script>

After clicking the Update button, output test_2. However, if text.value = 'test_1'; is commented out, the output result is quite different, test_0 is output.

Why is there this problem?

text.valueThe assignment operation is synchronous and real-time. When the code execution encounters a responsive state change, a view update logic## will be submitted. #Go to the microtask queue, and when nextTick is encountered, it will also be submitted to the microtask queue. So in the above code, View update logic is in front of nextTick, View update logic is executed by changing text.value = 'test_1' and text.value = 'test_2'Update the view after merging, so output test2;

Comment out

text.value = 'test_1',nextTick The order in the microtask queue is in front of View update logic, so test_0 is output.

defineComponent (auxiliary function for type inference, allowing TypeScript to correctly deduce the type in the component option)

If you use

752f0c4521bd75dec1baff2d2a067fcf syntax, you need to use defineProps to let TS derive the Props

<script setup lang="ts">
// 启用了 TypeScript
import { ref } from &#39;vue&#39;
const props = defineProps({ msg: String })
const count = ref(1)
</script>
<template>
  <!-- 启用了类型检查和自动补全 -->
  {{ count.toFixed(2) }}
</template>

if not used

setup Syntax, consider using defineComponent for wrapping to achieve type derivation

import { defineComponent } from &#39;vue&#39;
export default defineComponent({
  // 启用了类型推导
  props: {
    message: String
  },
  setup(props) {
    props.message // 类型:string | undefined
  }
})

If the project uses Webpack, please note that

defineComponent may cause the component to not be tree shaking, in order to ensure that the component is safely tree shaking, we need to do some processing during development

export default /*#__PURE__*/ defineComponent(/* ... */)

If the project uses Vite, there is no need to do any processing, because

Vite The underlying Rollup will intelligently think that defineComponent has no side effects.

defineAsyncComponent (asynchronous component)

During the development process, there are some scenarios such as: forms in pop-up boxes, components under other tabs, etc. do not need to be loaded during page initialization. We can consider using

defineAsyncComponent to declare it as an asynchronous component to improve the speed of page initialization.

Usage one (get components from the server)

import { defineAsyncComponent } from &#39;vue&#39;;
const AsyncComp = defineAsyncComponent(() => {
    return new Promise((resolve, reject) => {
        // ...从服务器获取组件
        resolve(/* 获取到的组件 */);
    });
});

Usage two (load local components asynchronously)

import { defineAsyncComponent } from &#39;vue&#39;;
const AsyncComp = defineAsyncComponent(
    () => import(&#39;./components/MyComponent.vue&#39;)
);

defineAsyncComponentOther parameter configuration

 const AsyncComp = defineAsyncComponent({
        // 加载函数
        loader: () => import(&#39;./Foo.vue&#39;),
        // 加载异步组件时使用的组件
        loadingComponent: LoadingComponent,
        // 展示加载组件前的延迟时间,默认为 200ms
        delay: 200,
        // 加载失败后展示的组件
        errorComponent: ErrorComponent,
        // 如果提供了一个 timeout 时间限制,并超时了
        // 也会显示这里配置的报错组件,默认值是:Infinity
        timeout: 3000
    });

Suspense

bb06e69d307cb52103d07d8f9dd385e5 is a built-in component used to coordinate the processing of asynchronous dependencies in the component tree. It allows us to wait higher up the component tree for multiple nested asynchronous dependencies below to be resolved, and render a loading state while waiting.

Although

defineAsyncComponent has loadingComponent parameters to configure the Loading component when loading asynchronous components, in some scenarios, it is necessary to use Suspense of. For example: A component depends on B, C, and D. If all three are asynchronous components, the loading process will display three Loadings, and Suspense can configure all sub-components to have actual Loading when they are not loaded.

defineCustomElement (Using Vue components to develop Web Components)

For an introduction to

Web Components, please refer to the article Getting Started with Web Components

Vue provides a and definitions Generally, Vue components have almost the same

defineCustomElement method to support the creation of custom elements.

import { defineCustomElement } from &#39;vue&#39;;
const MyVueElement = defineCustomElement({
    /* 组件选项 */
});
// 注册自定义元素
customElements.define(&#39;my-vue-element&#39;, MyVueElement);

The above is the detailed content of How to use Vue3 general API function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete
Previous article:How to use Vuex in Vue3Next article:How to use Vuex in Vue3