Ways to change the value of a property in reverse

I have a question about Vue and whether it is possible to achieve the opposite of using props. Let me clarify further with an example. Consider the following:

const app = Vue.createApp({
  data: function() {
    return {
      text: "Hello"
    }
  },
  template: `<div>
    <child-input v-model:text="text"></child-input>
      <input v-model="text" />
      {{text}}
    </div>`
})

In this scenario, if I set a prop in the child-input component with the name "text", its value will be synced with the external one. It would look like this:

const childInput = { 
data() { 
    return { input: '' }
  },
  props : ['text'],
  template: '<input type="text" v-model="outsideInput">',
  created() {
    this.input = this.text
  }
}

Now, if I create a watcher for the "text" variable to update the input value, it works. However, what I want to achieve now is the opposite - when the input in childInput (named "input") changes, I want this change to reflect on the external input as well.

Answer №1

To trigger an event from a child component and update a prop in Vue, you can follow this example:

const app = Vue.createApp({
  data: function() {
    return {
      text: "Hello"
    }
  },
  template: `<div>
    <child-input @text-changed="updateText" v-model:text="text"></child-input>
      <input v-model="text" />
      {{text}}
    </div>`,
  methods: {
    updateText(val) {
      this.text = val
    }
  }
})
app.component('childInput', { 
  props : ['text'],
  template: '<div> child <input type="text" v-model="input"></div>',
  computed : {
    input: {
      get(){
        return this.text
      },
      set(newValue) {
        this.$emit('textChanged', newValue)
      }
    }
  },
})

app.mount("#demo")
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo"></div>

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

Dispatch is functioning properly, however the state remains unchanged

I'm currently developing an application that utilizes redux for state management. In a particular scenario, I need to update the state. Here is how my initial state and reducer function are set up: import { createSlice } from '@reduxjs/toolkit&a ...

Correlating Mailgun Webhook event with Mailing list email

Recently, I have started using the Mailgun API to send emails and have also begun utilizing their mailing list feature. When sending to a mailing list, such as [email protected], I receive a single message ID. However, when receiving webhook responses, t ...

"Enhance your client-side PDF capabilities with the pdfMake plugin, offering support for multiple languages

I am in search of a plugin that can convert HTML content into a PDF format and is compatible with javascript/jQuery/AngularJS. It must also provide multilingual support. I have experimented with the following two plugins, but encountered limitations with ...

MapBox notifies when all map tiles have finished loading

Currently, I am utilizing the Mapbox GL JS API to manipulate a Mapbox map. Prior to sending my result (which is a canvas.toDataURL) to the server via HTTP, I must resize my map to a larger resolution and then use fitbounds to return to the original points. ...

Securing RESTful APIs with stringent security measures

Lately, I've been delving into using modern front end technologies such as React and Angular. This has led me to explore tools like JSON Server for simulating restful database interactions. I've noticed that most REST APIs require authentication ...

Searching through the use of autocomplete with alternative parameters

In the example below, - https://codesandbox.io/s/g5ucdj?file=/demo.tsx I am aiming to achieve a functionality where, with an array like this - const top100Films = [ { title: 'The Shawshank Redemption', year: 1994 }, { title: 'The Godfa ...

extract objects from an array of objects based on a specified array

Within my JSON array, I have data structured like this: const data = [ { "uniqueId": 1233, "serviceTags": [ { "Id": 11602, "tagId": "FRRRR", "missingRequired&quo ...

Script fails to load upon accessing page through index hyperlink

I am facing an issue with my JavaScript elements not loading when I navigate to a form page from a link in the index. However, if I enter the URL manually or redirect from the login page, the JavaScript loads perfectly fine. The JavaScript code is consolid ...

Troubleshooting Problems with Deploying Next Js on Firebase

I am currently working on a new Next Js application and have successfully deployed it on Vercel by linking the GitLab project. Now, I need to deploy the same project on Firebase. Here's what I have tried so far: - Ran firebase init This command gen ...

An issue occurred while deploying Docker on Railway services: Build Error

After successfully deploying my Django project on Railway, I decided to add SendGrid mail functionality using the django-sendgrid-v5 package. Everything worked fine in the development environment, including sending emails like user signups. However, when ...

Animate the sliding of divs using the JavaScript animation function

I've designed some boxes that function similar to notifications, but now I want to smoothly slide them in from the left instead of just fading in. I know that I need to use .animate rather than .fadeIn to achieve this effect. The code snippet I&apos ...

Changing URI to File Object using JavaScript

I have successfully retrieved the URI of a selected file in my Ionic app using the cordova-fileChooser plugin. https://i.sstatic.net/NxXti.jpg Next, I used the cordova-plugin-filepath to obtain the absolute path of the file from the nativeURL on the phon ...

Creating a dynamic image binding feature in Angular 8

I am working with an object array that requires me to dynamically add an image icon based on the type of credit card. Typescript file icon: any; savedCreditCard = [ { cardExpiryDateFormat: "05/xx", cardNumberLast: "00xx", cardId: "x ...

Issue encountered during installation of the robotjs npm package

Would appreciate any assistance with troubleshooting this issue. I've been grappling with it for 3 days, putting in countless hours of effort. The problem arises when attempting to install the robotjs npm package, as errors keep popping up. I've ...

Creating a fetcher that seamlessly functions on both the server and client within Nextjs 13 - the ultimate guide!

My Nextjs 13 frontend (app router) interacts with a Laravel-powered backend through an api. To handle authentication in the api, I am utilizing Laravel Sanctum as suggested by Laravel for SPAs. This involves setting two cookies (a session and a CSRF token) ...

Exploring the functionalities of the useState object with mapping techniques

While attempting to convert my class-based component to a functional style, I encountered the following code: const [foo, setFoo] = useState(null); const [roomList, setRoomList] = useState([]); useEffect(() => { setRoomList(props.onFetchRooms(props.to ...

What causes the other array to be affected when one is changed?

Take a look at this snippet of JavaScript code: var x = [1, 2, 3], y = x; y[1] = 3; x; // x === [1, 3, 3] Why does this happen? Why is the value of "x" changing when I update "y[1]"? I tried it in both Firefox and Chrome and got the same result. Th ...

React App searching for unused static files

Currently, my React application is deployed on the Nginx web server. Accessing the application using the URL XX.XX.XX.XX works fine. However, I want to be able to access it through the URL XX.XX.XX.XX/myapp/frontend. To achieve this, I have set up a revers ...

When trying to assign the result of res.send() to another variable in NodeJS Express, it does

My current Express version is 3.4.4 and I encountered an issue when trying to implement the following code: var cb = res.send; cb(result); This resulted in an error message: ...\node_modules\express\lib\response.js:84 var HEAD ...

Tips for emphasizing a searched item in V-data-table using VueJS

Is it possible to highlight a specific value in a v-data-table by searching for a particular word? Below is a snippet of my current code: EDIT: I am using the CRUD-Actions Example from the official Vuetify documentation. https://vuetifyjs.com/en/componen ...