I am trying to resize a DIV block using Vue3 but the button when I click it brings up an "Cannot read properties of undefined (reading ‘style’)". I know the JS part is wrong, but how do I correct it.
Here’s the HTML part of the code
<div ref="block2">
<button v-on:click="changeWidth()"></button>
</div>
Heres the JS:
methods: {
changeWidth:function()
this.$refs.block2.style.width = "150px";
}
}
And this is the CSS styling on the DIV:
#block2{
position:absolute;
z-index:5000;
width:50px;
height:50px;
background-color: #7d7d7d;
transition: all .3s ease-in;
}
Any help really appreciated
3
Answers
Silly, I just needed to add
You are correct, the JS has the problem also the HTML.
This is the correct code:
HTML:
JS:
I hope it helps:)
Since you want to perform the operation on button press, in my examples, there is always a variable to capture the current state and a variable for the input field. Of course, it could also be made dynamic so that resizing occurs simply when the input field changes without the need for a button press.
In Vue 3, I recommend abandoning the use of the Options API that was popular in Vue 2 and instead follow the guidelines of the Composition API. It lends a much more dynamic coding style to Vue.
Solution # 1: Resizing using the REF Element
I declared the container as a ref named
container
. Additionally, I created aresize()
function that runs on button press. At that point, I pass the value ofcurrentValue
to thestyle.width
andstyle.height
attributes of the ref component.Solution # 2: Resizing using the CSS attributes
I declared a variable called
nowValue
, in which I store the current pixel size of the container. I created aresize()
function that runs on button press and copies the value ofcurrentValue
from the input into thenowValue
variable. There are various ways to usenowValue
in the CSS code; currently, I simply passed the values in a style HTML attribute. This way, whennowValue
is updated, the DOM automatically takes on the new values.