formsvue.jsvuejs3vue-events

vue.js: How to dynamically change the value of a input field with the content from an other and still use value?


I have a firstName and a lastName input field and want to concat both at the name input field, e.g.

<input id="firstName" :value"firstName" />
<input id="lastName" :value"lastName" />
<input id="name" :value"{{ firstName }} {{ lastName }}" readonly />

If I modify the value of the firstName or lastName field, the name input field should update the result.

I have a script which fill the firstName and the lastName fields with data from a GET request.

<script>
  export default {
    data () {
      return {
        data: {},
        firstName: "",
        lastName: "",
      },
    },
    methods: {
      getUser() {
        this.$axios({method: 'get', url: 'http://127.0.0.1:8000/api/get_user/',
      }).then(response => {
        this.data = response.data;
        this.firstName = this.data.firstName;
        }
      }
    }
  }
</script>

I know that I cannot use v-bind and v-model together. But how could I solve this issue?


Solution

  • Create a computed property called fullName with getter/setter then bind it to the v-model :

    computed: {
      fullName: {
         get(){
            return this.firstName + ' ' + this.lastName;
         },
         set(val){
       
         }
    },
    
    <input id="firstName" v-model="firstName" />
    <input id="lastName"  v-model="lastName" />
    <input id="name" v-model="fullName" readonly />