Using v-model in a child component and setting v-model within a child component in a Vue project

How can I simplify this code?

Ensure that the button also updates the localValue of the child component.

Vue.component('my-input', {
  template: `
    <div>
      <b>My Input:</b> <br>
      localValue: {{ localValue }} <br>
      <input v-model="localValue">
    </div>
  `,
  props: ['value'],
  data() {
    return { localValue: this.value }
  },
  watch: {
    value () {
      this.localValue = this.value
    },
    localValue () {
      this.$emit('input', this.localValue)
    }
  }
})

new Vue({
  el: '#app',
  data: () => ({
    parentValue: 'Inital value'
  }),
  methods: {
    change () {
      this.parentValue = 'Changed value'
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <my-input v-model="parentValue"></my-input>

  <button @click="change">Change</button><br>

  parentValue: {{ parentValue }}
</div>

I have always struggled with this task.

Your assistance will be greatly appreciated!

Answer №1

If you decide not to utilize v-model within your custom form component, all you really need is:

<b>My Input:</b> <br>
localValue: {{ value }} <br>
<input :value="value" @input="$emit('input', $event.target.value)">

No need for creating data or using watch, that's all it takes.

For more information, refer to https://v2.vuejs.org/v2/guide/components.html#Using-v-model-on-Components


If you truly want something that represents a local value within your component, the Vue documentation suggests using computed values instead of watchers (reference: https://v2.vuejs.org/v2/guide/computed.html#Watchers).

The concept is to create a computed value with getter and setter to simplify the one-way data flow.

Vue.component('my-input', {
  template: `<div><b>My Input:</b> <br>localValue: {{ localValue }} <br><input v-model="localValue"></div>`,
  props: ['value'],
  computed: {
    localValue: {
      get () {
        return this.value
      },
      set (value) {
        this.$emit('input', value)
      }
    }
  }
})

new Vue({
  el: '#app',
  data: () => ({
    parentValue: 'Initial value'
  }),
  methods: {
    change () {
      this.parentValue = 'Changed value'
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <my-input v-model="parentValue"></my-input>

  <button @click="change">Change</button><br>

  parentValue: {{ parentValue }}
</div>

Answer №2

How to send intricate objects to child component and pass them down multiple layers:

Parent component:

<child v-model='parentObj' />

Child component:

model: {
    prop: 'modelValue',
    event: 'update:modelValue',
  },
  props: {
    modelValue: {
      type: Object,
      required: true,
    },
  },
...
obj: {
      // getter
      get() {
        return Object.assign({}, this.modelValue);
      },
      // setter
      set(newObj) {
        this.$emit('update:modelValue', newObj);
      },
    },
...

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 is the process for assigning a serial number to each row in the MUI DataGrid?

Initially, the server is accessed to retrieve some data. After that, additional data is added. While the data does not contain an ID, the form must still display a serial number. const columns: GridColDef[] = [ { field: 'id' ...

Ensure that the fields in Laravel 5.7 are properly validated by using asterisks and the required_if

My Vue form allows users to add work experience to their profile, with the option to add additional experiences by clicking a button. The structure of the form is illustrated below: <div class="item"> <div class="row"> <div clas ...

Using Ajax to Receive Data in a Separate JavaScript Function

I have a scenario where I am making an AJAX call in one function and attempting to capture the result in another function. Let me explain this in detail below: function myMain(){ var test = myWPackage(); alert(test); } function myWPackage(){ ...

Struggling to create a regular expression for a particular scenario

I'm dealing with nodes and currently faced with the task of applying a UNIX-like grep command to filter out specific content from an HTTP GET response. Below is the raw text received as the body variable: <?xml version="1.0" encoding="UTF-8" stand ...

Issues with unchecking modal icheck box when closing in Bootstrap JavaScript

Here is the HTML code that I am working with: <div class="modal inmodal" id="handleUserModal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> &l ...

I am receiving a 401 error when attempting to verify the token following a successful login

I've been working on a small project utilizing VueJS, Vue Router, and Laravel for the backend. Despite several attempts, I haven't been successful in implementing navigation guards. My login component is functioning properly. Here's my log ...

Maximizing the Efficiency of jQuery and Javascript Frameworks

Currently, I am working on a project that involves utilizing a JavaScript framework (jQuery) in conjunction with various plugins (validation, jquery-ui, datepicker, facebox, and more) to enhance the functionality of a modern web application. However, I ha ...

What is the best way to send props to a React component?

Sorry for the inconvenience of asking for help with finding an issue in my code, but I'm facing challenges while learning React. I am attempting to pass a variable named hashRoute to a component in react. However, every time I try to access the prop ...

Querying MongoDB to locate an element within an array is a common task

I need help with writing a mongoose query to select a specific object from the "cartItems" array in my mongodb database and update its "qty" and "price" fields. Here is the data: { _id: new ObjectId("634a67e2953469f7249c9a7f"), user: new ObjectId("634 ...

Turn off sticky sidebar feature for mobile-friendly layout

I have encountered an issue with my script that I need assistance with. I am trying to disable this script for responsive or mobile view, but despite trying various methods, it is not functioning as expected. <script type="text/javascript"> $(func ...

Can a specific element be chosen based on its background color?

Is it possible to change the background color of a child element within a div that has a specific background color using CSS? See my explanation below. For example: .container[background-color=some color] .content { background-color: some other color ...

"Encountering an 'Undefined function' error while implementing AJAX in the code

I'm encountering the issue Uncaught ReferenceError: GetLicenceUserList is not defined in the browser console when I utilize the function with $.ajax inside. However, the function works perfectly fine when I invoke it with just an alert("example& ...

Tips for passing data to a child component from a computed property

Currently in the process of setting up a filter using vue-multiselect. Everything seems to be working fine, but there's one issue I can't seem to resolve. Upon page reload, the label (v-model) appears empty. The root cause seems to be that the v ...

Am I on the right track with incorporating responsiveness in my React development practices?

Seeking advice on creating a responsive page with React components. I am currently using window.matchMedia to match media queries and re-rendering every time the window size is set or changes. function reportWindowSize() { let isPhone = window.matchMed ...

The output.library.type variable in WebPack is not defined

Currently, I am delving into WebPack with a shortcode. As part of my learning process, I am working on a code snippet that involves calculating the cube and square of a number, which are then supposed to be stored in a variable outlined in the webpack.conf ...

What is the best way to showcase a collection of items using a table layout in JavaScript?

I am relatively new to React/JS programming and I'm struggling to understand why my code isn't working correctly. My goal is to create a column with rows based on the items in my Array, but only the header of the table is displaying. After looki ...

Testing React components with Jest by mocking unnecessary components

Consider a scenario where we have the Page component defined as: const Page = () => <> <Topbar /> <Drawer /> <Content /> </> When writing an integration test to check interactions within the Drawer and Con ...

Determining the width of an element in Chrome using jQuery

Before adding an element to the body, I require its width. The code below functions correctly in Firefox, however it does not work properly in Google Chrome. <style> .testDiv { width:150px; height:100px; } </style> <script> var di ...

Retrieve the value of the target element when the Quasar q-checkbox is checked

I'm currently utilizing QUASAR and encountering an issue where I am unable to retrieve the state of my q-checkbox to determine whether it is checked or not. Despite using event.target.checked and event.target.value, both return as undefined. Below is ...

Discovering complimentary number sequences amidst intersecting number sequences

I have a specific number of arrays, each containing a set amount of elements. Each element consists of two attributes represented by numbers. { start: x end: y } These start and end numbers define a range, where the start value is always smaller tha ...