Home >Web Front-end >Vue.js >How to get elements and modify element styles in vue3
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='div' style='width:'50px'>
②In the script part, import ref and nextTick
import { ref,nextTick} from 'vue'
③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
Complete operation example code:
<div ref='div' style='width:'50px'>
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!