Vue3 Event Handling - Attempt to access an undefined property while rendering the component

Just starting out with Vue and JavaScript, but making progress!

Currently working on a Vue Main App that includes a sub-component for a form (specifically to calculate the difference between 2 values).

I want the form values to reset to their initial state when the "Reset" button in the main App is clicked.

However, I'm facing two issues:

  • Clicking the "Calculate Difference" button reloads the page.
  • The "Reset" function doesn't seem to reset the values back to the initial state as expected. It appears that the event is not properly reaching the sub-component.

Upon loading the page, I encountered a warning message that I am unable to decipher:

[Vue warn]: Property "reset" was accessed during render but is not defined on the instance. at

Below is a sample of the entire one-page code:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <title>Difference</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>

  <div id="app">

    <br> Modify Values, Click "Calculate Difference", then "Reset" to Set Back to 0
    <br>
    <calculator v-on:reset="reset" :start_val="0" :end_val="0"> </calculator>
    <br>
    <button class="button" v-on:click="onResetButton()"> Reset </button>

  </div>
</body>

<script>
  const vm = Vue.createApp({
    emits: {
      'reset': null
    },
    methods: {
      onResetButton() {
        console.log("emitting onResetButton")
        this.$emit('reset');
      },
    },
  })

  vm.component('calculator', {
    props: ['start_val', 'end_val'],
    data() {
      return {
        calculator: {
          start_val: this.start_val,
          end_val: this.end_val,
          difference: this.end_val - this.start_val,
        },
      }
    },
    methods: {
      onDifference() {
        console.log("calculating difference...")
        this.calculator.difference = this.calculator.end_val - this.calculator.start_val
        console.log(this.calculator.difference)
      },
      reset() {
        calculator.start_val = this.start_val
        calculator.end_val = this.end_val
        caculator.difference = this.end_val - this.start_val
        console.log("resetting calculator")
      }
    },
    template: `
            <hr>
            <form>
                <br> Start Value : <input class="input" type="number"  v-model.number="calculator.start_val">
                <br> End Value   : <input class="input" type="number"  v-model.number="calculator.end_val">
                <br> <button class="button" v-on:click="onDifference()">Calculate Difference  </button>
            </form>
            <p>Difference : {{ calculator.difference }} </p>
            <hr>
  `
  })

  vm.mount('#app');
</script>

</html>

Answer №1

Check out this snippet for some inspiration:

const {
  reactive,
  ref,
  toRefs,
} = Vue

const ExampleComponent = {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const textValue = ref(props.value)
      
    const handleChange = (event) => {
      textValue.value = event.target.value
    }

    return {
      textValue,
      handleChange
    }
  },
  template: `
    <div>
      <label for="input">Input:</label>
      <input id="input" v-model="textValue" @input="handleChange">
      <p>Entered Value: {{ textValue }}</p>
    </div>
  `
}

const vm = Vue.createApp({
  components: {
    ExampleComponent
  }
})

vm.mount('#app')

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

Tips for dynamically inserting JSON data into HTML elements

{ "top10": [ { "state": "red", "claimed": true, "branch": "release-2.3.4", ...

Determine if a draggable item is currently positioned over another element

In my body, there are several divs located: <div id="one"></div> <div id="two"></div> <div id="three"></div> All of these divs are draggable using jqueryUI: var $divs = $('#one, #two, #three'); $divs.draggab ...

The Magento 1.9.2.1 Observer for catalog_product_save_before appears to be malfunctioning and is not triggering as expected

After countless Google searches and reviewing answers from Marius and Alan Storm, I am still unable to figure out why my observer is not firing as expected. I have experience with observers, cleared the cache multiple times, tried different syntaxes for c ...

managing information through the elimination of nested keys with node js / javascript

let json=[ { metadata: { tags: [] }, sys: { space: { sys: [Object] }, id: '4gSSbjCFEorYXqrgDIP2FA', type: 'Entry', }, fields: { richTextEditor: { 'fn-US': [Object] }, short: { 'as-ds': &a ...

Middleware in Express not producing results

Here is the code I am currently using: var express = require('express'); var app = express(); app.use(express.bodyParser()); app.use(express.cookieParser()); var port = Number(process.env.PORT || 5000); app.get('/test/:id', function(r ...

Is it possible to prioritize loading JavaScript before images on a webpage?

My goal is to prioritize loading the js first and then the images for a specific reason. I want the blue rollover effect to be applied immediately upon loading. As the number of images on this page will eventually double, this could potentially become a la ...

Client component in Next.js is automatically updated upon successful login

I am currently working on a Next.js + DRF website that requires authentication. I have set up my navbar to display either a "log in" or "log out" button based on a boolean prop passed from the server side to the client-side: export default async function R ...

Vue routing stops working when there is no hash in the URL (no designated input file)

I am facing the need to operate Vue router in its default mode, known as hash mode, and unable to use it in history mode. In this mode, all my dynamic routes have a leading hash, like http://myurl.com/#/highlights. However, removing that initial hash, such ...

Functionality of the button disabled in Firefox, despite working perfectly in Chrome

I have been developing a ReactJS application that is now live. Take a look at the deployed version to understand the issue I am facing. In Firefox, the Login button in the Inventory Login section doesn't seem to be working as expected. Despite having ...

Exploring bidirectional component binding within Vue.js

As a newcomer to Vue.js, I was attempting to incorporate the currency filter example from the official guideline (example of currency filter). However, I encountered an issue when changing the property name of the component from 'value' to &apos ...

How to redirect from a method in Vue.js using Vue-router versions older than 1.x.x

While I don't consider myself a frontend developer, my knowledge of JavaScript is sufficient to complete basic tasks. Currently, I am working on integrating a login feature into my application, and I'm facing some challenges with my Vue component ...

How can you implement a repeating carousel with JavaScript?

I recently came across some carousels on and was intrigued by how they smoothly repeat the slides. Instead of jumping back to the first slide when reaching the end, it seamlessly transitions from the final slide back to the first one. I am eager to learn ...

JavaScript event manually triggered not propagating within an element contained in an iFrame context

I am currently developing a WYSIWYG designer that enables users to choose colors through [input type="color"] fields. The interface includes inputs on the left side and an iFrame on the right side displaying the generated preview. Normally, when ...

sequenced pauses within a sequence of interconnected methods in a class

scenario: There are two javascript classes stored in separate files, each utilizing a different external service and being called within an express.js router. Refer to the "problematic code" section below: route routes.post('/aws', upload.sing ...

JavaScript: Various Outputs Depending on Input

There seems to be a discrepancy in the results when I input "coup," "cou," and then "coup." Can anyone offer insight into why this might be happening? To view my code on jsfiddle, click here: jsfiddle.net/xbuppd1r/43 var data = {"cards":[{"$type":"Assets ...

When the loop is malfunctioning due to a certain condition

what happens if the condition in the controller file is not executed during runtime... ...

Having trouble accessing the session of next-auth.js within my _app.js file

I'm facing an issue where I have two providers, but I can't use both of them simultaneously. When I try to log in a user using useSession, I get an existence time error and not a user (an empty object is returned). I have a backend that returns t ...

A guide on retrieving query string parameters from a URL

Ways to retrieve query string parameters from a URL Example Input - www.digital.com/?element=fire&solution=water Example Output - element = fire solution = water ...

Troubleshooting: React.js State not updating properly on forms

New to React and facing a challenge with changing the state of form inputs. Here's what I'm trying to do: constructor(props) { super(props); this.state = { pwd:'', email:'', value:'' ...

Cease all playback of audio immediately

My goal is to ensure that any audio that has been played previously stops before a new audio clip starts playing. This will prevent overlapping clips on elements that may trigger the audio file multiple times. I have attempted to pause and reset the curre ...