3
votes

A Vue instance can allow you to create nested view models. For example, consider the following

new Vue({
  el: '#app',
  data: {
    form: {
      firstName: "Joe",
      lastName: "Bloggs"
    }
  },
  computed: {
    name: function () {
        return this.form.firstName + ' ' + this.form.lastName;
    }
  }
});

As you can see, there is a nested form-data object: form.firstName and form.lastName. I can bind this view-model to HTML with the following:

<div id="app">
  <form>
    <label>
      First:
      <input type="text" v-model="form.firstName">
    </label>
    <label>
      Last:
      <input type="text" v-model="form.lastName">
    </label>
  </form>
  <div>
    You are: {{name}}
  </div>
</div>

Here's a JS Fiddle for this Vue.js example

Now, my question is: is there a simple way (e.g. a directive) to create a nested binding scope that allows me to address firstName and lastName without the preceding "form."?

Knockout.js has the with binding that allows you to explicitly specify a binding scope in relationship to your view-model. Here is a JS Fiddle showing Knockout.js using the with binding

Is there a simple analogue to Knockout's with binding in Vue?

1
as far as I know, no way. You can address to firstName and lastName only by preceding "form". Btw, example in vue looks simpler than in knockout. - Nazgul Mamasheva
As @NazgulMamasheva pointed out, you can't do it exactly like that. However, you can always make the form a stand-alone component and pass it the form data object as a prop. - kano

1 Answers

0
votes

As long as you don't have repeated values, you could alias it to a computed property like

computed: {
  firstName: function() {
    return form.firstName
  },
  lastName: function() {
    return form.lastName
  }
}