简体   繁体   中英

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.

Use computed properties .

var app = new Vue({
  el: '#app',
  data: {
    firstname: '',
    lastname: ''
  },
  computed: {
    fullname: function(){
        return this.firstname + ' ' + this.lastname;
    }
  }
});

You have a property that is dependent on other properties. So use computed.

var app = new Vue({
  el: '#app',
  data: {
    firstname: '',
    lastname: ''
  },
  computed: {
    fullname: function () { 
      return `${this.firstname} ${this.lastname}` 
    }
  }
})

There is this exact example in the doc .

Working code snippet, with some additional checks, so the fullname is editable too:

 var app = new Vue({ el: '#app', data: { firstname: 'Foo', lastname: 'Bar' }, computed: { fullname: { // getter get: function () { return this.lastname ? this.firstname + ' ' + this.lastname : this.firstname }, // setter set: function (newValue) { if (newValue.indexOf(' ') !== -1) { var names = newValue.split(' ') this.firstname = names[0] this.lastname = names[1] ? names[1] : '' } else { this.firstname = newValue } } } } })
 <div id="app"> <label>Insert your first name:</label> <input type="text" v-model="firstname"> <label>Insert your last name:</label> <input type="text" v-model="lastname"> <label>Insert your full name:</label> <input type="text" v-model="fullname"> </div> <script src="https://unpkg.com/vue@2.4.2/dist/vue.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM