bidirectional communication using v-model in vue components

There is a component with a shared v-model, identical to the parent component. Here is the code snippet:

Vue.component('greeting', {
  template: '<input type="text" :name="name" v-on:input="updateSearch($event.target.value)"> ' ,
  props: ['name'],
  methods: {
    updateSearch: function(value) {
      this.$emit('input', value);
    }
  }
});
const app = new Vue({
  el: '#app',
  data: {
    name: ''
  }
});
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4234372702706c746c7b">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  
  Child: <greeting v-model="name"></greeting>
  <br><br><br>
  Main: <input type="text" v-model="name" placeholder="" />

</div>

If a user inputs text in either input box, I need both of them to be updated. Any suggestions on how to achieve this would be appreciated.

Answer №1

When you provide an object reference as a prop, you have the ability to bind a property of that object in both the parent and child components.

Vue.component('greeting', {
  template: '<input type="text" v-model="name.value" />' ,
  props: ['name']
});


const app = new Vue({
  el: '#app',
  data: {
    name: { value: '' }
  }
});
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cbbdbeae8bf9e5fde5f2">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  
  Child: <greeting v-bind:name="name"></greeting>
  <br><br><br>
  Main: <input type="text" v-model="name.value" placeholder="" />

</div>

Answer №2

It is generally not recommended to change props within a child component. One approach is to create two separate variables and update one when the other changes its value (using events and props).

For example, the greeting component could emit an event that you can catch in the main component and use to update the name.

Conversely, the main component could pass a prop to the greeting component that reacts to changes within the main component, updating the name variable in the greeting's data.

If you encounter more situations like this, consider utilizing vuex

Answer №3

If you're searching for it, the solution lies in using the .sync modifier for events within Vue.js version 2.3.0+.

For a detailed demonstration, you can refer to my article available here.

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

When using Angular, it is important to remember that calling `this.useraccount.next(user)` may result in an error stating that an argument of type 'HttpResponse<any>' cannot be used with a 'Useraccount' balance

When attempting to use this.useraccountsubject(user) to insert information upon login, I encountered an error: ErrorType: this.useraccount.next(user) then Error An argument of type 'HttpResponse' is not allowed against a balance of 'Userac ...

What is causing the issue preventing me from running npm run dev on CentOS 7?

Currently facing an issue while trying to install my application on a new server after migrating from centos6 to centos7. When attempting to install a Laravel app, everything goes smoothly as it did on centos6, except for when I run npm run dev [root@v6-a ...

How to extract iframe page title with jQuery in JavaScript

Is there a way to retrieve the title of an iframe's source page and then update the title of the main page? ...

The integration between babel-plugin-module-resolver and Jest seems to be broken

Although Babel alias works for test files by itself, it is not functioning properly for imports in Vue files. When Jest attempts to import a file in a Vue file, an error occurs as shown here. I added moduleNameMapper to the Jest configuration, but it onl ...

What is the process of assigning a string from an external PHP file to a JavaScript variable?

Recently, I've been experimenting with reading data from an external PHP file using Ajax. My goal is to store this data in a Javascript variable, but I'm unsure if my current approach is correct. Should I define the variable within the Ajax brack ...

TypeScript is unaware that a component receives a necessary prop from a Higher Order Component (HOC)

My component export is wrapped with a higher-order component (HOC) that adds a required prop to it, but TypeScript seems unaware that this prop has already been added by the HOC. Here's the Component: import * as React from "react"; import { withTex ...

Having trouble accessing the record by clicking on a table cell

I'm attempting to dynamically click on a cell within a row by passing the text of the cell. Here is my code: await element.all(by.xpath('//div/table/tbody/tr')).then(rows => { rows.find(row => { return row.all(by.tagName(&apo ...

going to ('/') doesn't lead anywhere

Currently, I am utilizing React Router Dom version 6. As part of my web application functionality, I have created a Redux action named "logoutUser" in my userAction. In the dashboard view file "dashboard.jsx", I have implemented a logout button that should ...

After resizing, reordering, hiding, or showing columns in the kendo grid, the grid's data source will be set to

I am encountering an issue with my kendo grid where the data disappears after performing certain actions: Reordering columns using mouse drag and drop Resizing columns using mouse drag and drop Hiding columns through the column menu Showing columns throu ...

React Native: Image not aligning vertically center in text within nested elements

Issue Description I am facing a challenge in nesting multiple images within a paragraph. If it were just a single line of text, I could have easily used a <View> with flexDirection: 'row'. Since that approach doesn't fit the requireme ...

Ways to incorporate active class in vuejs using router-link?

I need help with adding an active class to markers (such as .selecttasks) when clicking on a router-link. Here is the code snippet: .navigation ul li router-link(:to="{ name: 'tasks'}") Tasks li router-link(:to="{ name: ...

Implementing a recurring interval for a timer

Currently, I am attempting to create a stopwatch using the following code: var min = 0, sec = 0, censec = 0 $("#startBtn").on("click", function() {// upon clicking start button $(this).hide();// hide start button $("#stopBtn").show();// show stop butto ...

Converting a Ruby array into a KnockoutJS object

I'm having an issue with converting a Ruby array to JSON, saving it to MySQL, and then loading it into KnockoutJS. The problem is that the array remains a JSON string and I can't iterate over it. tags = `/usr/bin/svn ls #{svn_repo_url}`.split("/ ...

Execute a query in Firestore with a "where" filter

I am trying to filter and retrieve specific items based on the categoryID using the "where" method and the "==" operator. In my Firestore collection named "task", each user has a document with an array of different tasks. Here is the structure: Click here ...

How to insert a row above the header in an Excel sheet using JavaScript within

i am using excel js to export json data to excel. The json data is successfully exported to the sheet, but now I need to add a row that provides details of the sheet above the header text. for more details please refer image the code is shown below: i ...

Changing the Redux state within a custom hook will not trigger a re-render

I recently created a custom wrapper-hook for a Redux slice to avoid using the "{ type: x, payload: y }" syntax :p) Below is the code for the slice: // polycanvas.ts (Redux) export const polycanvas = createSlice({ name: 'polycanvas', initial ...

I encountered a SyntaxError that reads "Unexpected token instanceof" while using the Chrome Javascript console

I find it quite surprising that the code below, when entered into the Chrome JavaScript console: {} instanceof Object leads to the error message displayed below: Uncaught SyntaxError: Unexpected token instanceof Could someone kindly explain why this ...

Locate the closest pals near my present whereabouts

Is it possible to find my friends by obtaining their location from their mobile phones when they are near me? I have a code snippet below with the variable cities where I can input the numbers of my friends. Can I achieve this or do I need to make some m ...

How can I use React to dynamically generate text fields when a button is clicked, and continue adding more text fields each time the button is clicked again?

const [showNotes, setShowNotes] = useState(false); const generateNotes = () => { setShowNotes(true); <TextField id="notesField" label="Add your note here" variant="outlined"/> }; <div style = {{ display: ...

Tips for sending an email without using MAILTO in JavaScript or jQuery

Today is a great day for many, but unfortunately not for me. I've been struggling with this issue for over two weeks now and can't seem to find a solution anywhere on the internet. Stack Overflow always comes to my rescue when things get really t ...