Home > other >  How to inverse modify value of a prop
How to inverse modify value of a prop

Time:04-30

I've got a doubt regarding if there's a way in Vue to do the same as a prop but in the inverse way. Let me explain a bit better, so for example, I've the following:

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

In here if I define a prop in the child-input component with the name "text" I will have the exact same value as outside. Something like this:

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

And If I define now a watcher on the "text" variable to change the value of the input it does change. But now I would like to do the inverse, when the input of childInput (variable "input") changes, to propagate this change to the outsider input too.

CodePudding user response:

You can emit event from child and update prop:

const app = Vue.createApp({
  data: function() {
    return {
      text: "Hola"
    }
  },
  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>

  • Related