Home > Web Front-end > Vue.js > body text

How to use Vue3 general API function

王林
Release: 2023-05-14 22:31:04
forward
1103 people have browsed it

General API

version (exposes the currently used Vue version)

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

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>
Copy after login

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>
Copy after login

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

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template