Switching the Vue.js model linked to a form by selecting an item from a list

I am working with an array of objects that are being displayed in a list using vue.js. In addition to this list, I have a form that should show data from a specific object when one of the list elements is clicked.

How can I achieve this functionality in Vue.js?

The code for my list is as follows:

<div id="app-7">

                <ul id="food-list" v-cloak>
                    <food-item v-for="item in foodList" v-bind:food="item" v-bind:key="item.id" inline-template>
                        <li class="food">
                            <div class="food-header">
                                <img :src="'img/' + food.slug +'.png'">
                                <div class="food-title">
                                    <p>{{food.name}} |
                                        <b>{{food.slug}}</b>
                                    </p>
                                    <p>quantity: {{food.quantity}}</p>
                                </div>
                                <div class="food-load"> // bind this object's data to the form upon clicking
                                </div>
                            </div>
                        </li>
                    </food-item>
                </ul>

</div>

Answer №1

Without access to the code for the form, my best guess is as follows.

To make an item clickable, you can attach a click event handler that will pass the food item value to a method.

<div class="food-load" @click="setFoodItem(item)">
</div>

Once the method is triggered, it can store the clicked item in a data property. If the form is located in a different component, you may need to pass the item as a prop or emit an event to send it to the parent component.

data() {
    return {
        // A reactive field to hold the current object for the form.
        foodItemForm: null
    };
},
methods: {
    // Method to set the current item for the form.
    setFoodItem(item) {
        this.foodItemForm = item;
    }
}

Answer №2

Your code sample is missing important information that would help to understand your goal and identify any issues. Here are the key problems I found in your code:

  1. The v-for loop refers to each food item as 'item', but you are trying to access properties using 'food'
  2. You should only wrap your code in a component if you are importing the component
  3. When binding a value to 'v-bind:src' (or ':src' shorthand), only pass the URL and specify this in your script, not inline
  4. Consider using a button with 'v-on:click' ('@click') to load the selected food item into your form
  5. Make sure to include your JavaScript code

Based on what you have provided, here's how I suggest handling this scenario:

    <template>
        <div id="app">
    <ul id="food-list">
      <li v-for="item in foodList" class="food">
          <div class="food-header">
            <img :src="item.slug" v-bind:alt="item.slug" width="250px" height="auto">
            <div class="food-title">
              <p>{{item.name}} | <b>{{item.slug}}</b></p>
              <p>quantity: {{item.quantity}}</p>
            </div>
            <button class="food-load" @click="loadFoodItem(item.id)">Load Food Item</button>
          </div>
        </li>
    </ul>

    <form v-if="activeFoodId != null" id="foodItemForm" action="#">
      <h3>Food Form</h3>
      <label for="food-id">Id:</label>
      <input id="food-id" type="number" v-bind:value="foodList[activeFoodId].id"><br/>
      <label for="food-slug">Slug:</label>
      <input id="food-slug" type="text" v-bind:value="foodList[activeFoodId].slug"><br/>
      <label for="food-name">Name:</label>
      <input id="food-name" type="text" v-bind:value="foodList[activeFoodId].name"><br/>
      <label for="food-quantity">Quantity:</label>
      <input id="food-quantity" type="number" v-bind:value="foodList[activeFoodId].quantity">
    </form>
  </div>
</template>

<script>
export default {
  name: 'app',
  data: function () {
    return {
      activeFoodId: null,
      foodList: [
        {
          id: 1,
          slug: 'http://3.bp.blogspot.com/-QiJCtE3yeOA/TWHfElpIbkI/AAAAAAAAADE/Xv6osICLe6E/s320/tomato.jpeg',
          name: 'tomatoes',
          quantity: 4
        }, {
          id: 2,
          slug: 'https://img.purch.com/rc/300x200/aHR0cDovL3d3dy5saXZlc2NpZW5jZS5jb20vaW1hZ2VzL2kvMDAwLzA2NS8xNDkvb3JpZ2luYWwvYmFuYW5hcy5qcGc=',
          name: 'bananas',
          quantity: 12
        }, {
          id: 3,
          slug: 'https://media.gettyimages.com/photos/red-apples-picture-id186823339?b=1&k=6&m=186823339&s=612x612&w=0&h=HwKqE1MrsWrofYe7FvaevMnSB89FKbMjT-G1E_1HpEw=',
          name: 'apples',
          quantity: 7
        }
      ]
    }
  },
  methods: {
    loadFoodItem: function (foodItemId) {
      console.log(foodItemId)
      this.activeFoodId = foodItemId
    }
  }
}
</script>

<style>
  /# Irrelevant #/
</style>

I hope this solution helps!

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 tool can be used for formatting and syntax highlighting when working with ejs (embedded javascript) templates?

When working on my project, I utilize EJS as the express templating engine. While it is user-friendly and efficient, I have encountered difficulties when it comes to editing files - the text highlighting could be better, and I have not been able to find an ...

Looping through a single object with an Ajax call

When I make this ajax call, it only displays the last object from the JSON file instead of all objects. Can someone help me understand why? Ajax Call var ajax = new XMLHttpRequest(); var data = 'data.json'; var url = 'http://localhost: ...

Ways to verify that express middleware triggers an error when calling next(error)

I attempted to capture the error by using next() when stubbing it, but unfortunately it did not work. Below is the function: async getUser (req, res, next) { try { if (!req.user) { throw new CustomError('User not found', 404) } ...

Is it possible to utilize types as constants in a switch statement?

In my file called checkoutTypes.ts, I have defined some checkout types like this: export type CheckoutInvoiceAddressSection = "InvoiceAddress"; export type CheckoutDeliveryAddressSection = "DeliveryAddress"; export type CheckoutDelivery ...

Iterate through every item in Google Docs and duplicate them onto a fresh page

I am currently developing a script that allows teachers to easily create translations of documents stored on Google Drive. The script is expected to go through the body elements of the document, translate the text, and paste it onto a new page appended to ...

Unable to trigger jQuery onclick event on nested div elements

I'm experiencing an issue with my web-page where two buttons at the top are not responding to a sorting function on the nested #byFilter. Despite trying to apply the onclick(function()) method, it doesn't seem to work. Javascript $(document).re ...

What is the manual way to activate Ratchet's push feature?

I am facing an issue with a link that triggers a search function. Currently, the link is working as expected. However, I am having trouble getting the search to be executed by pressing the 'enter' button. Here is my code snippet: $('#sea ...

Unable to locate webpack module

When I try to run the command npm run start, I encounter an error message: The webpack configuration is as follows: "name": "frokify", "version": "1.0.0", "description": "frokify project", ...

Determine how the scale of a transform changes over time by calculating the function of elapsed time [ transform: scale(x, y

I am currently working on a container that can be expanded and collapsed simply by clicking on a chevron icon. The functionality to collapse or expand the container resides within a function called transformAnimation. This function code closely resembles t ...

Ways to receive JavaScript console error messages to aid in debugging your code

Currently, I am developing a Web Application and facing an issue with capturing console errors. Specifically, I need to capture errors related to network connectivity issues, such as when the network is down or slow causing responses from the server to be ...

Struggling with the integration of a custom login feature using next-auth, leading to being constantly redirected to api/auth/error

Currently, I am facing a challenge while working on my Next.js application. The issue lies with the authentication process which is managed by a separate Node.js API deployed on Heroku. My objective is to utilize NextAuth.js for user session management in ...

Issue encountered when attempting to push jQuery AJAX requests into an array

I'm attempting to store ajax requests in an array called deferreds. However, I'm consistently encountering the error message below: Uncaught SyntaxError: missing ) after argument list As a reference, I've been using this guide: Pass in an ...

One of a kind v-select options specifically tailored for each row in a v-data

I need assistance in creating a table with a v-select for each row of the "available" column to allow users to select either "In stock" or "Unavailable". How can I achieve this using the table provided below, which includes the following data? Table: < ...

What is the proper way to invoke a function that is part of a child component as a property in a React application?

In my app.js file, I have included a unique component called "SigningComponent" with the following code: onSign = () => { this.setState({ route: "home" }); }; registerFunction = () => { this.setState({ route: "registration" }); }; render() { ...

Combine the values of two text fields from separate input fields to populate a new text field across several lines

https://i.sstatic.net/fp8aZ.png I am seeking a way to automatically calculate the total cost by multiplying the quantity and unit cost values for each line entered. Despite my attempts with the jQuery script provided below, I have been unable to achieve t ...

Deleting a button from a list item or array in Angular 12

Having some trouble removing a list item with the click button, I've tried a few options but nothing seems to be working. Can anyone offer assistance? I need to remove a list item from my users array when clicked. Below is the Typescript code and cor ...

Automatically updating div content using a static HTML page

Is there a way to refresh the content of an HTML div tag every 5 minutes without having to reload the entire page? <div id="pie"> <script src="index.js">// this script should be reloaded every 5 minutes </script& ...

Please incorporate the href attribute into the anchor tag when it is clicked

<section> <a **id="download"** oncontextmenu="return false" > <svg ... </svg></a> </section> <script type="text/javascript"> The following code snippet is designed to ...

What is the best way to leverage a webbrowser control for design purposes while keeping the functionality in C#?

Observing some apps, it seems they utilize HTML/CSS/Javascript for styling - a much simpler approach compared to crafting the same thing natively. However, these apps have their logic written in C#. Sadly, I am clueless on connecting the two. Research yiel ...

Steps for embedding JavaScript code within HTML tags using a JavaScript file

Working on a React web app, I am solely using js and css files without any html. In one of my js files, there is a mix of html and js code like this: class Teams extends Component { state = { teams: [] } componentDidMount() { ...