Adocad
Adocad

Reputation: 751

Vue js: Is it posible to initialize data through a method?

Basically I want to initialize my vValidNombre field on my form by comparing two values, so It would be nice to use a method, something like this:

<script type="text/javascript">
  var avatar = new Vue({
    el: '#validaciones',
    data: {
      vNombre: $('input[name=nombre]').val(),
      vValidNombre: validar(),
    },
    methods: {
      validar: function(){
        if ('true' == 'true') {
          return = true;
        }
        else {
          return false;
        }
      }
    }
  })
</script>

This code doesn't work, but is it possible to do something like that?

EDIT: I'm using Vue 2

Upvotes: 0

Views: 4464

Answers (1)

Mozammil
Mozammil

Reputation: 8750

Not really. When it is initialised, vValidNombre would be undefined. However, you can do something like this with the ready method:

var avatar = new Vue({
    el: '#validaciones',
    data: {
        vNombre: $('input[name=nombre]').val(),
        vValidNombre: null,
    },

    ready: function() {
        this.vValidNombre = this.validar();
    }

    methods: {
      validar: function(){
          // do something here
          // and return it
      },

      bindDom: function() {

      } 
    },

})

Upvotes: 1

Related Questions