Home >Web Front-end >Vue.js >How to get elements and modify element styles in vue3

How to get elements and modify element styles in vue3

WBOY
WBOYforward
2023-05-18 23:16:202736browse

Requirements: Get the style of the element and modify the style of the element

The operation is mainly divided into the following parts. The complete code framework is attached at the end of the article

①Bind ref on the element to be operated

<div ref=&#39;div&#39; style=&#39;width:&#39;50px&#39;>

②In the script part, import ref and nextTick

import { ref,nextTick} from &#39;vue&#39;

③In the script part, make the element to be operated responsive, that is, bind ref

const div = ref()

④Using async await and nextTick

//需要在元素绑定函数a 这里忽略
async function a () {
  await nextTick()
    div.value.style.width="100px"

The difficulty is why we need to use async await and nextTick

If we don’t use it this way, an error will be reported: parameter 1 is not of type ‘Element’

The reason for this error is that the operator is operating an element that has not yet been rendered, or that the style he wants to operate does not have a corresponding element yet

After we learn vue3, we understand that the Dom has been updated after nextTick, so by combining async await and nextTick, the element can be effectively modified after rendering.

The following picture is from the vue3 official document

How to get elements and modify element styles in vue3

Complete operation example code:



The above is the detailed content of How to get elements and modify element styles in vue3. 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