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
Release: 2023-05-18 23:16:20
forward
2746 people have browsed it

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

②In the script part, import ref and nextTick

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

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

const div = ref()
Copy after login

④Using async await and nextTick

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

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:



Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template