Utilizing Props in Vue.js to Access Data for v-model

After browsing online, I attempted to pass props to data in the following manner:

Child Component:

props: {
  idInput:   { type: String, required: false },
  nameInput: { type: String, required: false },
},
data() {
  return {
    id: this.idInput,
    name: this.nameInput,
  }
}

This allows me to utilize it here:

<t-input v-model="name" type="text" />

Parent Component:

data() { return { game: {} } },
beforeCreated() { this.game = { name: "myName", id: "myID" }
<ChildComponent :name-input="game.name" :id-input="game.id" />

The issue arises when "name" appears as undefined. However, if I alter it to "nameInput", it functions properly but triggers a Vue error warning against using props that way. Any suggestions?

Answer №1

Below is a practical demonstration I put together to illustrate this scenario:

const component = Vue.component('component', { 
  template: '#myComponent',
  props: {
    idInput:   { type: String, required: false },
    nameInput: { type: String, required: false },
  },
  data() {
    return {
      id: this.idInput,
      name: this.nameInput,
    }
  }
});

new Vue({
  el: "#myApplication",
  data () {
    return {
      game: {}
    }
  },
  created() {
    this.game = { name: 'selectedName', id: 'chosenID' };
  },
  components: { component }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="myApplication">
  <component :name-input="game.name" :id-input="game.id" />
  {{game}}
</div>

<template id="myComponent">
  <div>
    {{idInput}}
    <br>
    <input v-model="name" type="text" />
  </div>
</template>

UPDATE: Upon reviewing the code, it appears that the issue lies in setting the game attribute in the data of the parent component during beforeCreated. Adjust it to be set during created instead.

REVISED The original poster discovered an alternative approach. Rather than passing individual props, pass a single prop containing the object and utilize its attributes with v-model.

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

Is the term "filter" considered a reserved keyword in Angular, Javascript, or ASP.Net MVC?

When using angularJS to call an ASP.Net MVC controller from a service, I encountered an issue with one of the parameters: $http({ method: "get", url: "ControllerMethod", params: { param1: param1Value, pageNumber: pageNumber, ...

I am looking for a way to retrieve the ids of all div elements that have the same x coordinate using document.elementFromPoint in JavaScript. Can someone help me with

Currently, I am facing an issue where I have two divs positioned at the same x coordinate. I am attempting to retrieve the IDs of both divs using document.elementFromPoint(). However, I am only able to receive the ID of one div. var elem = document.elem ...

Avoid clicking in areas outside the perimeter of the blue circle in the SVG

Is there a way to restrict clicking outside the blue circle? The goal is to only allow opening by clicking on the svg itself, This includes everything, even white space inside the svg. How can this be achieved in the code? The current behavior is that ...

Creating a polyBezier or polyCurve with Canvas HTML: a step-by-step guide

Looking to connect several points with a curve rather than just a straight line. I attempted using the lineTo() and bezierCurveTo() methods to draw the points. Is there anyone who can assist me in solving this dilemma? Perhaps there is a different approac ...

Tips for sending a JavaScript object from PHP to AJAX

I've been racking my brain for hours, scouring through countless articles, but I'm still unable to crack this puzzle. Here's the situation: I'm currently tinkering with Chrome extensions and I need to make a server call that will fetch ...

Using headers in the fetch api results in a 405 Method Not Allowed error

I am facing an issue while attempting to make an ajax request using fetch. The response I receive is a 405 (Method Not Allowed) error. Here is how I am trying to execute it: fetch(url, { method: 'get', headers: { 'Game-Toke ...

What is the process for reaching application-level middleware from the router?

Within my project created using express application generator, I am facing a challenge accessing my application-level middleware from the router. This middleware is specifically designed to query the database using the user ID that is received from the ro ...

Trying out a newly added function in a Vue.js/Nuxt.js component to test its dynamic capabilities

Currently, I am designing a test for dynamically generated methods within a particular component. The code snippet is outlined below: <template> <div id="app"> <div @click="executeDynamic('myCustomFunction& ...

What is the best way to display an image in Vuetify when the URL is found within my filtered array?

I need to display various images depending on the card being loaded. <tr v-for="location in filteredLocation" v-bind:key="location"> <v-card class="mx-auto"> <v-img class="white--text align-end" height="200px" ...

What are some strategies for optimizing the loading speed of Nuxt.js when using cloud functions?

While I have a strong preference for vue.js, upcoming projects require me to use Nuxt for better SEO ranking. Despite my limited experience setting up Nuxt, I found valuable tutorials on running an express app with Nuxt. Typically, I incorporate firebase f ...

Implement a contact form using backend functionality in a ReactJS application

Currently, I am in the process of developing my first website using reactjs. My focus right now is on completing the contact form page, and I have already spent 2 days on it. To handle email functionality, I am utilizing nodemailer with a Gmail account tha ...

Modifying static content within jQuery tabs

Encountering an issue with jQuery $('#tabs').tabs();. When checking out the example on JSFIDDLE, I noticed that the content containing an external php file is always displayed, even when switching to other tabs. <li class="files"> < ...

There seems to be a hiccup in the distribution build of Angular grunt, as it is unable to locate the

While testing the build, everything runs smoothly. However, when attempting to build the distribution, an error is encountered: An error occurred: Cannot find module '/Users/matt.sich/Documents/angularProjects/firstProject/node_modules/grunt-usemin/l ...

How can I preserve the line break in a textarea using PHP?

Is it possible to maintain line breaks in a textarea using PHP? Currently, I have a temporary solution that involves using the exec function to run a shell command, but I would prefer a purely PHP approach. Below is my temporary script - can you help me mo ...

How are objects typically created in Node.js applications?

These code snippets are from Node.js tests, and I am curious about why one method of instantiating an object is favored over another? // 1 var events = require('events'); var emitter = new events.EventEmitter(); emitter.on('test', doSo ...

The accuracy of getBoundingClientRect in calculating the width of table cells (td)

Currently, I am tackling a feature that necessitates me to specify the CSS width in pixels for each td element of a table upon clicking a button. My approach involves using getBoundingClientRect to compute the td width and retrieving the value in pixels (e ...

Error encountered while handling document events during server-side rendering in ReactJS

I am currently developing a React.js application that requires keyboard navigation for a horizontal scrolling carousel of items. In the existing version, only the left and right arrows are used for navigation, with Enter being used to make selections. I ha ...

When the button is clicked, bind the value to an object using the specified key in

I'm fairly new to Vue and I'm looking to generate buttons based on my data and show their information when clicked. The 'pets' object contains keys for id and info. (My actual data is more extensive and my code is a bit more complex, bu ...

Autocomplete feature in Material-UI does not trigger the onChange event when a chip

I've encountered a quirk with the Material UI Autocomplete component. It seems that when I delete a tag directly from the chip using the (x) button, the onchange function of the autocomplete isn't triggered. Does anyone know how I can ensure that ...

Is there a way to selectively display items that are grouped with children only?

I am currently experimenting with Vuetify and exploring the usage of v-list-group. I am curious to know if there is a way to prevent the grouping behavior for items that do not have any children? <template> <v-layout fill-height> ...