Utilizing Vue.js to dynamically update input fields based on other field values

I'm a beginner with Vue.js and Vuetify.js, and I am encountering some difficulties with the following:

<v-select v-model="car.type"
    :items="types"
    label="Type"
></v-select>

<div v-if="car.type === 'fiat'">
    <v-text-field v-model="car.km" label="KM"></v-text-field>
    <v-text-field v-model="car.color" label="Color"></v-text-field>
</div>

<div v-else-if="car.type === 'bmw'">
    <v-text-field v-model="car.color.first" label="First color"></v-text-field>
    <v-text-field v-model="car.color.second" label="Second color"></v-text-field>
</div>

While it somewhat works and changes the input fields based on the type, an error is appearing:

[Vue warn]: Error in render: "TypeError: undefined is not an object (evaluating '_vm.car.color.first')"

If I change the v-model to car.colorfirst, without the nested JSON object, it works. This could be because car.color.first is not defined yet. However, I need the other method to work.

Any suggestions on what to do? Does this make sense?

Check out the live demo here: https://codepen.io/alfredballe84/pen/MBXwKx

Answer №1

I have modified your html and js code for better functionality.

<div id="app">
  <v-app>
    <v-form>

      <v-select v-model="car.type" :items="types" label="Type"></v-select>

      <div v-if="car.type === 'fiat'">
        <v-text-field v-model="car.km" label="KM"></v-text-field>
        {{car.km}}
        <v-text-field v-model="car.color" label="Color"></v-text-field>
        {{car.color}}
      </div>

      <div v-else-if="car.type === 'bmw'">
        <v-text-field v-model="car.colorMore.first" label="First color"></v-text-field>
        {{car.colorMore.first}}
        <v-text-field v-model="car.colorMore.second" label="Second color"></v-text-field>
        {{car.colorMore.second}}
      </div>

    </v-form>
  </v-app>
</div>

Here is the updated vuejs code:

new Vue({
  el: "#app",
  data() {
    return {
      car: { "type": "fiat",color:"",colorMore:{} },
      types: ["fiat", "bmw"]
    };
  }
});

Remember to either use an empty object (like colorMore) for binding or simply utilize an element (like color) for binding.

You can view the modified code in this Codepen link: https://codepen.io/nikleshraut/pen/BPVNMv

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

"Looping through each item in a list using Angular

I have a setup for an HTTP request that will return the list of products once all promises are fulfilled. My objective is to initially set the opacity of these products to 0, and then use a forEach loop to add a class that sets their opacity to 1. While ...

Implementing callback within another function: A guide

I'm embarking on the journey of creating a node waterfall using the async module. I've just dipped my toes into the waters of asynchronous programming in node. Essentially - how do I trigger callback() within the http.request function to proceed ...

An easy guide to using validators to update the border color of form control names in Angular

I'm working on a form control and attempting to change the color when the field is invalid. I've experimented with various methods, but haven't had success so far. Here's what I've tried: <input formControlName="pe ...

The ValidationMessageFor tag is failing to function on the view page

I am currently in the process of updating the styling from bootstrap 3 to bootstrap 5. The issue I am facing is that in the bootstrap 3 version, when I click the "save" button without filling any text boxes, the page displays a validation message like this ...

Can you explain how this promise functions within the context of the mutation observer, even without an argument?

Recently, I came across a mutation observer in some TypeScript code that has left me puzzled. This particular implementation of a promise within the mutation observer seems unconventional to me: const observer = new MutationObserver((mutations: MutationR ...

Leverage the power of AJAX and PHP to securely save comments for future

I have coded a JavaScript function that uses POST and GET methods to send comments from an input field and retrieve them when the page reloads. However, I am unsure of how to handle the data after it is sent in order to save it and access it again later. E ...

What are the best strategies for creating HTML website designs that are both scalable, adaptable, and versatile?

As a beginner in HTML website design, I have recently started using HTML, CSS, jQuery, and JavaScript for designing websites. After creating a site with almost forty webpages, the client requirements are changing, requiring changes to be made across all ...

Guide on changing the CSS of MUI parent components to set the display of buttons to 'block' in React

I'm facing a challenge with my modal design for mobile view. I need the buttons to display in a stacked format, one above the other, taking up the full width of the modal. I've been exploring ways to override the existing CSS within the component ...

effective ways to extract objects from nested structures using a specific identifier

In this sample data, I am looking to filter an object based on its ID key let myData = { "nodeInfo": { "9": { "1": { "ID": "14835" ...

Troubleshooting 'Warning: Prop `id` did not match` in react-select

Having an issue with a web app built using ReactJs and NextJs. I implemented the react-select component in a functional component, but now I'm getting this warning in the console: Warning: Prop id did not match. Server: "react-select-7 ...

Unable to display child component using VueRouter

Recently, I started delving into VueJS and decided to create a new Vue application using vue-cli. After making a few modifications, this is what my router.js looks like: import Vue from 'vue' import Router from 'vue-router' import Hell ...

Could it be that the AmCharts Drillup feature is not fully integrated with AngularJS?

UPDATE: Check out this Plunker I created to better showcase the issue. There seems to be an issue with the Back link label in the chart not functioning as expected. I'm currently facing a challenge with the AmCharts Drillup function, which should a ...

The revalidateTag and revalidatePath features in Next.js are currently not functioning as expected

I attempted to utilize the revalidateTag and revalidatePath functions with Next.js version 14.2.3. The objective was: there is a server action to fetch a list of items. also, there is a server action to add an item. upon successful addition of an item, I ...

tips for utilizing namespaced getter filtering within a Vuex module in vueJs

In my custom module named ShopItemCategory, I have a Getter getters: { shopItemsCategories: state => state.ShopItemsCategories.data, }, Inside the component, there is a computed function I defined computed: { shopItemsCategories ...

Enhanced JavaScript Regex for date and time matching with specific keywords, focusing on identifying days with missing first digit

I have a specific regular expression that I am using: https://regex101.com/r/fBq3Es/1 (audiência|sessão virtual)(?:.(?!audiência|sessão virtual|até))*([1-2][0-9]|3[0-1]|0?[1-9])\s*de\s*([^\s]+)\s*de\s*((19|20)?\d\d) ...

What is the reason objects cannot be compared in JavaScript?

I have a straightforward code snippet here. Its purpose is to authenticate the user against the author of the post and grant the authenticated user access to edit the post. exports.edit = function(req, res){ Post.findById(req.params.post_id, function ...

The parameter type ‘DocumentData’ cannot be assigned to type ‘never’ in this argument

I've been struggling to find a solution to my issue: Ts gives me an error: Argument of type 'DocumentData' is not assignable to parameter of type 'never' I attempted the solution I found on this page: Argument of type 'Docume ...

AngularJs tip: Harness the power of parallel and sequential function calls that have interdependencies

service (function () { 'use strict'; angular .module('app.user') .factory('myService', Service); Service.$inject = ['$http', 'API_ENDPOINT', '$q']; /* @ngInject ...

Textbox with Placeholder Text and Entered Data

When working with an HTML input box to enter a value that will be used to run a PHP script, it is possible to pass that value using the URL and GET method. To enhance user experience, I wanted to add a watermark hint in my textbox. After some research, I ...

What exactly happens behind the scenes when utilizing the React hook useEffect()? Is an effect set up with useEffect able to halt the main thread

According to the documentation for the useEffect() hook in React, it states that: "Effects scheduled with useEffect don’t prevent the browser from updating the screen." Insight Unlike componentDidMount or componentDidUpdate, effects set with ...