VUE JS - My methods are triggering without any explicit invocation from my side

I've encountered a frustrating problem with Vue JS >.<. My methods are being triggered unexpectedly. I have a button that is supposed to execute a specific method, but this method gets executed along with other methods, causing annoyance...

Here is my form

<form class="row">
                <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 pr-xl-0 pr-lg-0 pr-md-0  m-b-30">
                  <div class="product-slider">
                    <img class="d-block" :src="image" alt="First slide" width="285" height="313">
                    Image URL <input type="text" @focusout="showPicture" id="imageLink">
                  </div>
                </div>
                <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 pl-xl-0 pl-lg-0 pl-md-0 border-left m-b-30">
                  <div class="product-details">
                    <div class="border-bottom pb-3 mb-3">
                      <h2 class="mb-3">
                        <input type="text" value="Product Name" minlength="4" id="name" required/>
                      </h2>
                      <h3 class="mb-0 text-primary">$<input type="number" value="1.00" step="0.01" id="price" required></h3>
                    </div>
                    <div class="product-size border-bottom">
                      <h4>Provider</h4>
                      <input type="text" value="Pro Inc." minlength="3" id="provider" required>
                      <div class="product-qty">
                        <h4>Quantity</h4>
                        <div class="quantity">
                          <input type="number" value="1" id="quantity" required>
                        </div>
                      </div>
                    </div>
                    <div class="product-description">
                      <h4 class="mb-1">Description</h4>
                      <textarea rows="4" cols="50" minlength="50" id="description" required>Sample Text</textarea>
                      <button :onclick="addProduct()" class="btn btn-primary btn-block btn-lg">Add to inventory</button>
                    </div>
                  </div>
                </div>
              </form>

and here's the complete script.

<script>
const DB_NAME = 'DBInventory';
const DB_VERSION = 1;
export default {
  data: function() {
    return {
      db:null,
      ready:false,
      addDisabled:false,
      image: "https://i.imgur.com/O9oZoje.png",
    };
  },
  async created() {
    this.db = await this.getDb();
    this.ready = true;
  },
  methods: {
    showPicture() {
      let link = document.getElementById("imageLink").value;
      if(link !== "")
        this.image = link;
    },
    async getDb() {
      return new Promise((resolve, reject) => {

        let request = window.indexedDB.open(DB_NAME, DB_VERSION);

        request.onerror = e => {
          console.log('Error opening db', e);
          reject('Error');
        };

        request.onsuccess = e => {
          resolve(e.target.result);
        };

        request.onupgradeneeded = e => {
          console.log('onupgradeneeded');
          let db = e.target.result;
          let objectStore = db.createObjectStore("products", { autoIncrement: true, keyPath:'id' });
          console.log(objectStore);
        };
      });
    },
    async addProduct() {
      this.addDisabled = true;
      let product = {
        name: document.getElementById("name").value,
        provider: document.getElementById("provider").value,
        price: document.getElementById("price").value,
        quantity: document.getElementById("quantity").value,
        description: document.getElementById("description").value,
        image: document.getElementById("imageLink").value,
      };
      console.log('about to add '+JSON.stringify(product));
      await this.addProductToDb(product);
      this.addDisabled = false;
    },
    async addProductToDb(product) {
      return new Promise((resolve, reject) => {
        //delete me
        console.log(reject);
        let trans = this.db.transaction(['products'],'readwrite');
        trans.oncomplete = e => {
          //delete me
          console.log(e);
          resolve();
        };
        let store = trans.objectStore('products');
        store.add(product);
      });
    },
  }
}
</script>

One of my methods triggers even when I'm not focused on the image input field. It does work, but it also triggers the addProduct(), which adds my item to the indexDB, something I only want to happen when I click the "Add to inventory" button.

This situation is quite confusing for me as I'm still learning Vue JS ^^' (I'm using Vue 3)

Answer №2

To prevent the function from executing automatically, it’s essential to include the function declaration in the onclick method. Give this code a try! I’m not experienced with Vue, but I can assure you it functions properly in React. Javascript is universal anyway.

:onclick="() => addProduct()"

Answer №3

Effective way to trigger click event in Vue.js complete procedure

<a v-on:click="addProduct"></a>

convenient method

<a @click="addProduct"></a>

Next, execute the addProduct function

addProduct: function () {
      ...
    }

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

Converting and saving geometry in three.js using the toJSON method and BufferGeometryLoader for serialization and deserialization. Transmitting geometries as text

Let me start by saying that I am new to three.js and would like to share my learning journey. My objective was to convert geometry into a format that can be transferred to another web worker (as not all objects can be transferred between workers, only s ...

Implementing HTMX with just one HTML page: A step-by-step guide

Just starting out with HTMX and created a sample: <!DOCTYPE html> <html> <head> </head> <body> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfema ...

Is there a way to create a function that can show the pathway on the Browser Console?

I am looking to create a function that will show the path in the Browser Console when a link in the menu of a sub-category is clicked. The menu setup resembles this () on an e-commerce website. For instance: Perfume => ForMen => Cologne How can I r ...

Framer Motion causes a crash in a Next.js application with the error message: "Unable to find named export 'useId'"

I am encountering an error in my Next.js app that I can't seem to trace back to its source. Strangely, the code triggering the error is not something I wrote myself. error - file:///Users/cheq/Desktop/cheqo/node_modules/framer-motion/dist/es/component ...

PHP is adding unique characters like   into the database records

Description : Having an issue with adding a text to a content editable div. When clicking the button, I am trying to extract all the text from the div and send it to php successfully. However, when saving it to my database table, the text gets corrupted. A ...

The JQuery.ajax function encountered an unexpected identifier and threw an Uncaught SyntaxError

Hey there, I'm encountering this error and I'm stumped: jQuery.ajax Uncaught SyntaxError: Unexpected identifier I'm attempting to pass some customer information to another file named "pricealarm.php" in the main directory of the FTP-Serve ...

Exploring Manipulation of M:N Associations in Sequelize

I have set up a sequelize schema using postgre DB export const Commune = sq.define("commune",{ codeCommune: { type: DataTypes.STRING(5), allowNull: false, primaryKey: true }, libelleCommune: { type: ...

What is the process by which React recreates the React element tree (virtual DOM) with every state update?

From what I've gathered, every time a state is updated in React, it generates the react element tree (virtual DOM) and then compares it with the new one using a diffing algorithm. However, there's something I find puzzling. Let's say we hav ...

Comparing the start and end times in tabular or array input using Yii2

Can I compare the start and end times in the Yii2 client/ajax validation for my form? This is how my view file code looks: <?php foreach ($model->weekDaysList as $index => $value) : ?> <div class="row"> <div class="col-sm ...

"Enhancing User Experience with Multiple Conditional Checkboxes in jQuery

Having difficulty making a checkbox change some HTML content using JQuery. There is a standard html checkbox with the following attributes <input type="checkbox" name="AQN1" class="checkbox Q1" value="AQN10" id="3mcq"> <input type="checkbox" nam ...

Basic Hover Effect in Javascript

Looking at this snippet of HTML: <div id="site-header-inner"> <div id="header-logo"> <?php echo wp_get_attachment_image(get_field('header_logo','options'),'full'); ?> </div> <div id= ...

Navigating through embedded arrays in Angular

JSON Object const users = [{ "name":"Mark", "age":30, "isActive" : true, "cars":{ Owned : ["Ford", "BMW", "Fiat"], Rented : ["Ford", "BMW", "Fiat" ...

Concealing alert messages automatically in CodeIgniter PHP after a certain amount of time

After attempting to use a script to hide the flash message once displayed, I found that it was not working as expected. The flash message remains visible until the page is refreshed. Controller: if ($this->email->send()) { $this- ...

Converting Node.js Date.toString() output into a time format in Go

My go service is currently receiving data from an external source. Here's how the data appears (in JSON format)- { "firstName": "XYZ", "lastName": "ABC", "createdAtTimestamp": "Mon Nov 21 2 ...

Having trouble retrieving data property in Vue 3: Error thrown (in promise) TypeError: Unable to access properties of undefined (reading 'variablename')

export default { data() { return { results: [], }; }, methods: { getData() { fetch("http://rb.test/api/posts/all") .then(function (response) { if (response.ok) { return response.json(); ...

Exploring ElectronJs: The journey to sending messages from ipcMain to IpcRender and awaiting a response

I need help with sending a message to ask the renderer to parse an HTML string mainWindow.webContents.send('parse html', { resp}) The renderer processes the data and sends a reply ipc.on('parse html',function(e,p){ let b ...

JS: The values printed by setTimeout are always taken from the previous iteration

This issue I'm facing is directly related to JS scope, and despite my efforts in research, I have not been able to find effective solutions from similar stackoverflow queries. Here is the program in question: http://jsfiddle.net/0z525bhf/ function ...

Generate a revised object from a function and return it to the caller

What is the most efficient way to update and return a new object from a function? I came up with this function: export const addItemToCart = (currentCart, item) => { const { name, ...otherProps } = item; // if the item is already in the cart if ...

The iFrame that is generated dynamically becomes null when accessed from a page that has been loaded using JQuery

One issue I am facing is with a dynamically created iframe in regular javascript. It functions perfectly fine when called from a static page using conventional methods. However, when it is being called from a page loaded by jQuery, I encounter an error s ...

Is there a correct way to accomplish this task? How could I go about achieving it?

Currently, I am delving into the world of react. While following along with some video tutorials, I encountered a roadblock in the request.js file. The issue popped up during the build process ./src/Row.js Line 16:45: 'fetchUrl' is not define ...