Home > Software design >  Do properties always need to be declared in data: { }
Do properties always need to be declared in data: { }

Time:10-28

I'm getting familiar with Vue.js after having previously used AngularJS and I'd like to find if there's any way to get around explicitly declaring every data property in data { }.

In AngularJS, it was enough to declare ng-model as an HTML attribute and when the app initializes it adds them to the scope so they can be read/manipulated.

My concern is that I have a technical calculator I'm making with about 100 individual properties and declaring each property twice seems redundant.

Does Vue offer anyway to implicitly pick up the model properties without explicitly declaring them in the app data?

Example AngularJS without explicitly declaring model properties in the app:

<script src="https://code.angularjs.org/1.6.9/angular.js"></script>
<div ng-app="exampleApp" ng-controller="exampleController">
    <input ng-model="firstName" ng-change="makeName()">
    <input ng-model="lastName"  ng-change="makeName()">
    <input ng-model="fullName">
</div>
<script>
    angular.module("exampleApp", []).controller("exampleController", function ($scope) {
        $scope.makeName = function () {
            $scope.fullName = $scope.firstName   " "   $scope.lastName;
        }
    });
</script>

More or less the same app in Vue.js:

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<div id="exampleApp">
    <input v-model="firstName" v-on:input="makeName">
    <input v-model="lastName" v-on:input="makeName">
    <input v-model="fullName">
</div>
<script>    
    var app = new Vue({
        el: '#exampleApp',        
        data: {
           firstName: "",
           lastName: "",
           fullName: ""
        }, 
        methods: {
            makeName: function () {
                this.fullName = this.firstName   " "   this.lastName;
            }
        }
    });
</script>

CodePudding user response:

Yes, for any 'variable' used in the HTML template, it must be declared in the JS.

While this can seem annoying when you have a lot of variables, it is important since the variable can be any one of a number of reactive things - simple variables, computed properties, methods etc. It wouldn't be possible to know what to create without also some syntax to specify what type of variable should be created, or to specify any default values.

In your example, fullName should probably be specified as a computed property - e.g.:

computed: {
  fullName: function () {
    return this.firstName   " "   this.lastName;
  }
}

This way there is no need for the v-on:input - when the firstName and lastName variables update, this will trigger fullName to be recalculated.

  • Related