What is the reason behind the functionality of this v-bind:value?

I'm currently working on a basket system that utilizes both Laravel and Vue. In my Vue file, cart.js, I have a data object structured like this:

data: {
  material: {
    id: '',
    qty: '1',
  },
}

When the user clicks on the 'Add to Basket' button on the product page, it triggers the following function:

addToBasket: function(){
  var that = this;
  var item = this.material;
  this.$http.post('/api/buy/addToBasket', item).then(response => {
    this.basketAddSuccess = true;
  }, response => {
      //error
  });
}

Unfortunately, this function fails with a 500 error because it appears that the id is not being properly bound to the Vue instance. Here's an extract of the view code:

<form v-on:submit.prevent="addToBasket(material)">
  <input type="hidden" v-model="material.id" v-bind:value="{{ $material->id }}">
  <div class="form-group">
        <label for="qty">Quantity</label>
        <input class="form-control" name="qty" type="number" v-model="material.qty" v-bind:value="1">
  </div>
  <button class="btn btn-block btn-primary">@{{ buttonText }}</button>
</form>

Despite Laravel correctly injecting the value as seen in the rendered code:

<input type="hidden" v-model="material.id" value="1">

The binding to Vue doesn't seem to be functioning. I've experimented with different combinations of v-model and v-bind without success. Any guidance would be greatly appreciated!

Answer №1

If you're using the v-model directive, make sure to set the value on the data object instead of the template. Here is a helpful explanation of how the v-model directive works behind the scenes: https://alligator.io/vuejs/add-v-model-support/

UPDATE 1: I have provided an example with multiple materials below:

The template

<template>
    <div class="materials">
        <form 
            class="material"
            v-for="material in materials"
            :key="material.id"   
            @submit.prevent="addToBasket(material)"
        >
            <div class="form-group">
                <label for="quantity">Quantity</label>
                <input type="number" name="quantity" :value="material.qty">
            </div>
            <button class="btn btn-block btn-primary">@{{ buttonText }}</button>
        </form>
    </div>
</template>

In the JavaScript code snippet provided, $materials is a Laravel PHP Array of Objects containing id and quantity keys.

export default {
    data() {
        return {
            basketAddSuccess : false,
            materials : {!! json_encode($materials) !!}
        };
    },
    methods : {
        addToBasket(material) {
            this.$http.post('/api/buy/addToBasket', material).then(response => this.basketAddSuccess = true).catch(error => console.log(error))
        }
    }
}

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

What steps should I take to update my Vue 2 components for use in Vue 3?

I am considering using my Vue 2 components in a new Vue 3 project, is this possible? For example, I currently have Vue 2 components for "FAQ" and "About Us". Can I incorporate these components into a Vue 3 project by creating routes to use them? I initiall ...

Terminating a function during execution in JavaScript/TypeScript

Currently, I am in the process of developing a VSCODE extension using TypeScript. Within this extension, there is a particularly large function that is frequently called, but only the final call holds significance. As a solution, I am attempting to elimina ...

Reformat the quantities in the array and then make necessary updates

I am working with pinia in a state that holds an arrangement of two quantities. A component I am using has a vueform slider with two inputs displaying the maximum and minimum values of the slider through v-model. The slider is set to accept minimum and max ...

DirectionsLight isn't functioning properly in Three.js

I attempted to add lighting in Three.js, but after updating the display, the light didn't seem to affect my cylinder. I simply copied and pasted the source code from the Three.js documentation Three.js as instructed, but to no avail. Below is the cod ...

Troubleshooting iFrame Loading Issues with HTML5 PostMessage

Our code is utilizing the newest postMessage feature in HTML 5 to address cross-domain communication challenges. The issue I am facing is figuring out how to determine if the messages posted to an iFrame have been successfully loaded. If the frame fails to ...

"An unexpected compilation error (800A03EA) has occurred in the JavaScript syntax during

My computer is facing a frustrating compilation issue with JScript and node. Despite trying various solutions found online, the problem persists. After navigating to CD>PROJECT: npm init successful npm install -g globally and locally installed corr ...

What is preventing me from retrieving the parameter in the controller?

I could use some assistance with implementing pagination for displaying data. However, I am encountering issues in retrieving the parameter in the Controller Method. To provide more context, I have created a demo on CodePen which can be viewed at http://c ...

Having trouble accessing the selected item in the $scope when using ng-options inside ng-repeat?

I am looking to achieve the following: I have an array called 'all' that contains all possible items. I want to create a subset of that array and store it in 'subset': JavaScript (js.js): var app = angular.module('myApp', [ ...

Trouble arises when attempting to delete rows from my database with the use of HTML, PHP, and

I am developing an application where I have implemented this table: <?php require_once 'Connect2db3.php'; ?> <form> <fieldset> <article class="rondehoeken"> <header> <div class="streep1"></div& ...

Issue with CSS files in Jest"errors"

I'm currently facing an issue while trying to pass my initial Jest Test in React with Typescript. The error message I am encountering is as follows: ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.App ...

Is it possible to create an input field exclusively for tags using only CSS?

I am currently facing some limitations with a website I am managing. Unfortunately, I do not have the ability to incorporate additional libraries such as custom jQuery or JavaScript scripts. My goal is to customize an input field for tags so that when us ...

Inserting an icon into a particular class

I am new to JavaScript and I am eager to understand the code I write rather than just using it. That's why I'm turning to this forum with a question regarding adding an icon to a colored group. Here is the code snippet I have: <strong> ...

Assign a value to an input element with JavaScript and retrieve the value using PHP

Below is a form and input element that can be found in the cart.php file: <form id="cartform" action="cart.php?action=update&pd=<?php echo $row['product_id'] ?>" name="form1" method="post"> <?php $query = "select * from ca ...

Best practices for utilizing the CASE WHEN statement in Laravel's Eloquent ORM?

I am trying to show the call and chat seconds while grouping the data by session_id without repetition. To achieve this, I am using a CASE WHEN statement to display only chat or call data based on the type. However, I am facing an issue where the CASE WHEN ...

JavaScript code to enforce a 100% page zoom setting

After developing a small game in Canvas, I encountered an issue. Some users with their default zoom level set to something other than 100% are unable to view the entire game page. I attempted to resolve this by using the following CSS: zoom: 100%; This ...

Having trouble with the npm package installation for react-circular-progressbar

I encountered an error when trying to install react-circular-progressbar in my React projects. Why is this happening? npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/em ...

Issue: Unspecified Index encountered when making an Ajax call

I'm encountering an issue where I am receiving an "Undefined Index" error while trying to call Ajax. My goal is to post JSON data to the "update.php" page when the submit button is clicked. Essentially, I want to gather the values in textboxes and sen ...

React component making repeated calls to my backend server

As a React newbie, I am currently in the process of learning and exploring the framework. I recently attempted to fetch a new Post using axios. However, upon hitting the '/getPost' URL, I noticed that the GetPost component continuously calls the ...

Unable to directly assign a variable within the subscribe() function

My goal is to fetch a single row from the database and display its information on my webpage. However, I've encountered an issue with the asynchronous nature of subscription, which prevents immediate execution and access to the data. Upon running the ...

Display the chosen date from the datepicker in the input field

Utilizing a JQuery DatePicker to be constantly displayed, I have assigned it to a div. Despite wanting it to display the selected date in the input box like in this example, it just isn't functioning as desired for me. Is there a way to have the selec ...