Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS data object is 2 data objects combined

So I have this basic VUE.js page, but I want variable C to be a composite of variable A and B together.

var app = new Vue({
  el: '#app',
  data: {
    firstname: '',
    lastname: '',
    fullname: firstname + lastname
  }
})

so I can use it in a <input type="text" v-model="fullname"> and it will contain the values of firstname and lastname.

firstname and lastname will be binded to 2 other inputs as follows:

<label>Insert your first name:</label>
<input type="text" v-model="firstname">
<label>Insert your last name:</label>
<input type="text" v-model="lastname">

so the fullname variable will be a dynamically binded firstname + lastname variable.

I've tried several things but I can't seem to get this working.

like image 986
Kevin Avatar asked Jul 28 '26 13:07

Kevin


1 Answers

Use computed properties.

var app = new Vue({
  el: '#app',
  data: {
    firstname: '',
    lastname: ''
  },
  computed: {
    fullname: function(){
        return this.firstname + ' ' + this.lastname;
    }
  }
});
like image 66
balping Avatar answered Jul 31 '26 01:07

balping



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!