0
votes

I am currently building a log in page for a personal project that I'm doing using Node.js and Vue.js and I'm having some trouble with data accessing between vue instances.

I currently have it working so that a text input box will have a error class assigned to it if a boolean data value is true. I have two separate Vues for the fields, a username input and email input:

var user = new Vue({

    el: '#usr-field',
    data: {
        hasError: messages.inUse.show || messages.tooShort.show
    }

});



var email = new Vue({

    el: '#email-field', 
    data: {
        hasError: messages.idLength.show
    }

});

Just about this in the same file is the Vuejs for the error messages that show up if there are any:

var messages = new Vue({

    el: '#errors', 
    data: {
        showErrors: false, 
        inUse: {
            show: false,
            text: 'The username you chose is already in use'
        }, 
        tooShort: {
            show: false,
            text: 'The username you chose is too short (4 character minimum)'
        }, 
        idLength: {
            show: false,
            text: 'The email you provided does not match the standard 7 character format'
        }
    },
    methods: {
        resetErrors: function() {
            if (this.showErrors) {
                this.showErrors = false;
                this.idLength.show = false;
                this.inUse.show = false;
                this.tooShort.show = false;
            }
        },
    }

});

The way I'm currently trying to dynamically access the values of the messages Vue isn't work except for on load. Is there a way I can have the user and email Vue's hasError data change dynamically in accordance with the messages Vue data?

1

1 Answers

1
votes

First, create only one Vue instance.

Use an element that includes your login form input elements. For ex. a div wrapper with id login.

new Vue({
  el: '#login', 
  data: {
      showErrors: false, 
      inUse: {
          show: false,
          text: 'The username you chose is already in use'
      }, 
      tooShort: {
        show: false,
        text: 'The username you chose is too short (4 character minimum)'
      }, 
      idLength: {
        show: false,
        text: 'The email you provided does not match the standard 7 character format'
      }
  },
  methods: {
    resetErrors: function() {
        if (this.showErrors) {
            this.showErrors = false;
            this.idLength.show = false;
            this.inUse.show = false;
            this.tooShort.show = false;
        }
    },
  }
});

Then in your HTML, use v-bind:class to show or hide your class error in your inputs, like this:

<input id="usr-field" :class="{'error': messages.inUse.show || messages.tooShort.show}" ...

Same idea for your email field:

<input id="email-field" :class="{'error': messages.idLength.show}" ...

If later you feel the need to isolate logic, you may want to look into components.