How can you synchronize a prop with the parent component in Vue?

I want to establish a bidirectional relationship between a component and its child. For instance, I have a common string that is passed to my sub-components:

<template>
  <div>
    <foobar title="Foo" :value.sync="shared"></foobar>
    <foobar title="Bar" :value.sync="shared"></foobar>
  </div>
</template>
<script>

import Sub from './sub'

export default {
  components: {
    'foobar': Sub
  },
  watch : {
    shared() {
      console.log("Shared value was updated")
    }
  },
  data() {
    return {
      shared: "Content"
    }
  }
}
</script>

Each subcomponent consists of a text input linked to this shared property:

<template>
  <b-form-group :description="title">
    <b-form-input v-model="value"></b-form-input>
  </b-form-group>
</template>
<script>
export default {
  props: {
    value: String,
    title: String
  }
}
</script>

The desired behavior is to always display the same value in both text inputs. If I change `Foo`, `Bar` should update and the watcher event `Shared value was updated` would be triggered.

However, instead of the expected outcome, I encounter the following error:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten 
whenever the parent component re-enters.

Answer №1

It is necessary to trigger an event in the child component.

I have not verified this code, but it should resemble something similar to the following:

<template>
  <b-form-group :description="title">
    <b-form-input :value="value" @input="$emit('update:value', $event.target.value)"></b-form-input>
  </b-form-group>
</template>
<script>
export default {
  props: {
    value: String,
    title: String
  }
}
</script>

Answer №2

Transform your fooBar component to incorporate prop as a v-model

<foobar title="Foo" v-model:value="sharedState"></foobar>

For further information, check out the linked documentation

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

Interact with the button through Swipe Left and Right gestures

Is it possible to trigger a button click using JQuery or JavaScript when swiping left or right on two buttons like these? <button id="right" type="button">SWIPE RIGHT</button> <button id="left" type="button">SWIPE LEFT</button> If ...

If the first element of the array contains all the letters of the second element, then return true

I attempted to tackle this challenge by creating a loop that iterates through the firstword each time a letter matches with a letter in the secondword. function mutation(arr) { var compare = []; var firstword = arr[0].toLowerCase(); var secondword = ...

Using multiple images to create a visual in three.js

Looking to create a unique shape or maybe even a word using three.js by incorporating various pictures. Take, for example, the following image: https://i.sstatic.net/9O1dF.jpg My plan is to determine the points that will form the desired shape and then p ...

Can you define the "tab location" in an HTML document using React?

Consider this component I have: https://i.stack.imgur.com/rAeHZ.png React.createClass({ getInitialState: function() { return {pg: 0}; }, nextPage: function(){ this.setState({ pg: this.state.pg+1} ) }, rend ...

Reset form upon submission

When submitting a form and adding the contents to an array, I encounter an issue where the item added to the array remains linked to the form. How can I add the item to the array and then clear the form, similar to using jQuery's reset() function? Be ...

Having trouble grasping the concept of setInterval()?

When using setInterval() to retrieve updated data and draw content at regular intervals, I noticed that in Internet Explorer it only functioned correctly the first time. After researching online, I came across suggestions that it might be due to caching is ...

Using array variables with v-bind:class does not apply classes as expected

Here is the vue-js code snippet I am struggling with: <table class="table table-sm user-perm-list"> <tbody v-for="index in totalUsers" v-bind:key="index"> <tr> <td> <div class="text-medium ...

Error message: "NAN encountered while attempting to extract a numerical value from

I've encountered a strange bug in my coding. I'm working on a weather forecasting website that uses geolocation to identify your city and then utilizes the wunderground API to provide the forecast. The issue arises when manually searching for a c ...

Utilize a for loop to load data using JSON

Here's a question for you. Take a look at my code snippet: var data=[]; for(i=0;i<parametrTable.length;++i){ x = parametrTable[i]; (function(i) { if(i==0){ $.getJSON("myurlwithparametr", function(json) { ...

Achieving Style= Background-Img URL Extraction with Cheerio

I am attempting to retrieve the URL of the background image. The background image is located within an a href tag. The a href tag contains the following style: style="background-img:url("")" I am using cheerio (a Node.js module simila ...

The error message encountered is: "Property 'http' cannot be found on type 'VueConstructor<Vue>' when using Vue-Resource with TypeScript."

I have been tackling a Typescript issue in a Vue project that relies on vue-resource. Despite the project functioning properly, I am encountering a typescript compiler error. https://i.sstatic.net/RFT8B.png https://i.sstatic.net/A2MZm.png I have managed ...

To address the issue of input values not persisting in a Selenium iframe element, I am implementing a custom JavaScript event to

Attempting to initiate a JavaScript 'change' event on an element within an iframe. The following is the code snippet I have been using: // accessing the iframe window var iframeDoc = document.getElementsByTagName("iframe")[0].contentWin ...

The synergy between ternary operators and Vue filters

Recently, I came across a peculiar issue while working with Vue. Take a look at the code snippet from vue.html: <label :text= "$props.information ? (($props.information.primary || $props.information.secondary) | myFilter) : `No info`"> </lab ...

Encountering an error in Strapi project: URL undefined

I am currently in the process of setting up a Strapi application and getting it up and running. Following the instructions provided in this document: After successfully setting up Strapi and creating the application, I encountered an error when trying to ...

Launching an online platform with Express and Ember frameworks

I am embarking on a project to create a straightforward CMS using Node.js (with Express) and Ember.js. While I have experience with Angular, I am new to Ember.js. I've noticed that Ember.js operates similarly to Angular in terms of its CLI reliance, a ...

Executing multiple database queries in JavaScript/Node.js without using chaining techniques

I've been experimenting with NodeJS and express for a while now, but I'm stuck on this particular issue. For the product page, my goal is to display: 1) The Product 2) Related Products I want to create reusable code that looks something like ...

send a variable to a function in a random sequence

In my code, I have a function defined as follows: let showNotification = function(a,b,c,d,e,f){ console.log(a,b,c,d,e,f); } When calling this function, it is crucial to pass parameters in the correct order. For example, if I want to omit values for c, ...

Personalize the year heading for v-date-picker

I am utilizing a date picker with the Japanese locale <v-date-picker locale="ja-jp" ></v-date-picker> This feature allows for kanji characters to be displayed for week/month/year. However, I am curious ...

Generating new elements on the fly using jQuery and passing a string parameter through the onclick event

While dynamically creating HTML, I encountered a syntax error. If I modify href="javascript:startChat(' + user_id + ','video')" to href="javascript:startChat(' + user_id + ','"video"')", I receive an error stating &a ...

Ensure the text area box is validated upon clicking a specific radio button

Hello, my HTML code looks something like this: <input type="radio" name='answer_value1[<?php echo $survey1->id?>]' value="<?php echo $answer1->id?>" validate="required:true" id="<?php $answer1->valdt == '1' ? ...