Search code examples
methodsvuejs2initialization

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


Solution

  • 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() {
    
          } 
        },
    
    })