Unable to adjust the size of a DIV with a button click in Vue3

I am having trouble resizing a DIV block in Vue3. Whenever I click the button, I receive an error message saying "Cannot read properties of undefined (reading 'style')". I know there is an issue with the JS part of the code, but I'm not sure how to correct it.

Here is the relevant HTML:

<div ref="block2">
<button v-on:click="changeWidth()"></button>
</div>

And here is the corresponding JavaScript:

methods: {
    changeWidth:function()
            this.$refs.block2.style.width = "150px";
         }     
}

The CSS styling for the DIV is as follows:

#block2{
    position:absolute;
    z-index:5000;
    width:50px;
    height:50px;
    background-color: #7d7d7d;
    transition: all .3s ease-in;
}

Any assistance would be greatly appreciated.

Answer №1

If you're looking to trigger the operation on a button press, my examples include variables to track the current state and input field. This setup can easily be modified to dynamically resize when the input field is updated without requiring a button press.

For Vue 3, it's advisable to move away from the Options API used in Vue 2 and embrace the Composition API for a more dynamic coding approach in Vue.

Approach #1: Resizing with REF Element

I've defined the container as a ref named container. Furthermore, I've implemented a resize() function that executes on button press. Within this function, the value of currentValue is applied to the style.width and style.height attributes of the ref component.

const { createApp, ref } = Vue

const app = createApp({
  setup() {
    const container = ref(null)
    const currentValue = ref(100)
    
    const resize = () => {
      container.value.style.width = `${currentValue.value}px`
      container.value.style.height = `${currentValue.value}px`
    }
    
    return { currentValue, container, resize }
  },
}).mount('#app')
.container {
  width: 100px;
  height: 100px;
  background: #363635;
  color: #fff;
  margin: 20px 0;
  overflow: hidden;
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5a3a0b095e6fbe6fbe1">[email protected]</a>/dist/vue.global.prod.js"></script>

<div id="app">
  <div ref="container" class="container"></div>
  
  <input v-model="currentValue" type="number" min="1">
  <button @click="resize">Resize container to {{ currentValue }}px</button>
</div>

Approach #2: Resizing using CSS Attributes

In this method, I introduced a variable called nowValue to store the current pixel size of the container. The resize() function updates the nowValue variable with the value of currentValue from the input field upon button press. Different approaches exist to leverage nowValue in CSS; in this instance, I directly set these values in a style HTML attribute. Consequently, any change to nowValue automatically reflects in the DOM.

const { createApp, ref } = Vue

const app = createApp({
  setup() {
    const nowValue = ref(100)
    const currentValue = ref(100)
    
    const resize = () => {
      nowValue.value = currentValue.value
    }
    
    return { currentValue, nowValue, resize }
  },
}).mount('#app')
.container {
  width: 100px;
  height: 100px;
  background: #363635;
  color: #fff;
  margin: 20px 0;
  overflow: hidden;
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4533302005766b766b71">[email protected]</a>/dist/vue.global.prod.js"></script>

<div id="app">
  <div class="container" :style="{ width: `${nowValue}px`, height: `${nowValue}px` }"></div>
  
  <input v-model="currentValue" type="number" min="1">
  <button @click="resize">Resize container to {{ currentValue }}px</button>
</div>

Answer №2

Indeed, there seems to be an issue with both the JavaScript and HTML in this case. Here is the corrected code: HTML:

<div id="block2">
  <button v-on:click="changeWidth()">Resize</button>
</div>

JavaScript:

methods: {
  changeWidth: function() {
    const block2 = this.$refs.block2;
    if (block2) {
      block2.style.width = "150px";
    } else {
      console.error("Element with ref 'block2' not found");
    }
  }
}

I trust this clarifies things for you:)

Answer №3

Oh my goodness, I can't believe all I had to do was include

id="block2"

Seems like everything is finally in order....

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When the tooltip component is triggered in a React application, the cursor is automatically directed to

I have been working on creating an input field that allows users to enter time as input. Here's the code snippet I am using: <InputMask mask="99:99" onBlur={handleOnBlur} onChange={(e) => { const ...

The mysterious anomaly in Vue.js

I am attempting to assign a data object named types upon receiving a response in the ready() method. This is what I have: export default { data () { return { types: null } }, ready () { TypeService.showAll(1) .then(functio ...

Best practices for alerting using React and Redux

As I delve into Redux for the first time and work on revamping a fairly intricate ReactJS application using Redux, I've decided to create a "feature" for handling notifications. This feature will involve managing a slice of state with various properti ...

Transfer spoken words into a textbox using the keyboard-microphone feature on an iPad or mobile device

When we tap on a textbox on an iPad or mobile device in a web browser, the keyboard pops up on the screen. We have the option to choose the microphone and dictate the text directly into the input box using our voice instead of typing. Since speech convers ...

The error of 'illegal invocation' occurs when attempting to use input setCustomValidity with TypeScript

I am new to the Typescript world and currently converting one of my first React applications. I am facing an issue while trying to set custom messages on input validation using event.target.setCustomValidity. I keep getting an 'Illegal invocation&apo ...

Unusual Occurrence: Unexpected Gap at the Beginning of HTML

There seems to be an issue with white space appearing unexpectedly at the top and right side of the file in a website I am working on. Despite adding margin: 0; padding: 0; to both <body> and <html>, the problem persists. After inspecting the ...

Field for text input enclosed within the <select> tag

I have a project where I am implementing a dropdown using AngularJS. Here is the code snippet: <div class="col-md-9"> <input type="text" placeholder="Enter Module" list="names" ng-model="data.Name" /> <select id="names" class ...

Issue with hiding div using jQuery's length option

I'm currently using Drupal 7.0 along with the Galleria Javascript Image Gallery in fullscreen theme. My theme includes two navigation buttons, and here is the CSS code for them: .galleria-image-nav { height: 159px; opacity: 0.8; position: fixed ...

Retrieve the maximum number of slots from a JSON file and implement them into the

I've encountered an issue with my upload form. After uploading and previewing an image, I want to add it to a list as long as the list still has available slots. Here's an example: If the maximum number of slots is set to 5, then you can add up ...

Unable to place a div below another div

I am in the process of creating a website for my mother, using my limited knowledge. Despite numerous attempts, I have not been able to achieve the desired outcome. Currently, the website looks like this: https://i.stack.imgur.com/ItOcp.jpg However, I e ...

JQuery fails to remove the "display:hidden" attribute

List of methods I attempted: Utilizing .removeClass and addClass functions Applying show() and hide() methods Modifying the CSS properties Initially, I confirmed that my script contains onLoad. Furthermore, all other elements are functioning correctly. D ...

Combine es6 imports from the identical module using an Eslint rule or plugin

Looking to consolidate my ES6 imports from a single module into one for my React project. For example: import { Title } from "@mantine/core"; import { Center } from "@mantine/core"; import { Divider } from "@mantine/core"; T ...

Express Server React 403 Forbidden Error

Issue: When attempting to make a post request using the AXIOS library in React, I am receiving a 403 (Forbidden) error for http://localhost:5004/api/auth/login. Despite having installed cors on Express, the console continues to display the 403 error. My c ...

Issue with the dynamic updating of props

Every time a radio button is clicked within Test.js, the handleclick function executes, updating an array. However, the issue lies in not sending this updated array back to graph_test.js. As a result, graph_test.js only receives the initial array filled wi ...

Chrome renders the javascript source file in a jumbled and unreadable format

I'm new to a project and I've noticed that the javascript files I edit in my IDE appear differently in Chrome. For instance, here is a code snippet from Intellij: https://i.sstatic.net/1ygfg.png Even though this code is in a file named MNV.js, ...

How to Perfectly Align a Gif

I'm trying to understand the functionality behind this code snippet. Can anyone shed some light on it? img{ display:block; margin:auto; } I attempted to center a gif using this code block after my teacher suggested trying align:center; without succe ...

What is the best way to display a single font in various sizes?

Have you ever noticed the unique typography on typedetail.com? The font sizes of the logo (TYPE DETAIL) and the title (ABOUT TYPE DETAIL) are different, with the first letters appearing larger than the rest. Surprisingly, upon inspecting the style sheets, ...

Utilizing React's useState to store data in local storage

I am trying to figure out how to save data from a photos database API into local storage using the useState hook in React. Despite my attempts, I have not been successful with the useState method as the data in local storage gets cleared upon page refres ...

JavaScript method to clear a variable

Can JavaScript prototype be used to add a method to a variable that is undefined? For instance, we can use the following code: var foo = "bar"; String.prototype.doTheFoo = function(){ console.log("foo is better than you"); }; foo.doTheFoo(); This c ...

Guidelines for redirecting an on-click action to navigate to a link rather than entering text

Using the AJAX Live Search PDO feature, I made a modification to have the displayed words link to their respective URLs. However, clicking on the table does not redirect to the link but instead inputs the text. I am looking for a way to make the entire row ...