0

Currently I am querying a Firebase database for the current users username. I would like the value to display on the page inside the <template> area. Looked through the docs but still new to Vue.

Everything will output into the console correctly, I am just unsure of the next step to reference inside the <template> using moustache handles eg. {{ user.username }}

  data() {
    return {
      userName: ''
    }
  },
  methods: {
    getName: function() {
      var userId = firebase.auth().currentUser.uid;
      return firebase.database().ref('users/' +
        userId).on('value', function(snapshot) {
        if (snapshot.val()) {
          var obj = snapshot.val();
          var userName = snapshot.val().username;
          console.log('username:', userName)
        }
      });
    }
  }

Template

<template>
 <span>{{ user.username }} (Output result of var userName here)</span>
</template>
2
  • I've never used vueJS, but have you tried {{ userName }} ? Commented Dec 26, 2017 at 15:59
  • You don't have a user data item. You have userName. You should probably set it in your .on callback, taking care to have this set properly. Commented Dec 26, 2017 at 16:39

2 Answers 2

2

You are getting the username, but you are not updating the vue instance object (the data object). You can call vueInstance.$set(vueInstance, 'propertyName', newPropertyValue); to update it (more details here):

new Vue({
  el: '#app',
  data() {
    return {
      message: 'Hello Vue.js!',
      userName: ''
    }
  },
  methods: {
    getName: function() {
      var vueInstance = this;
      return setTimeout(function() {
        var userName = 'new username';
        vueInstance.$set(vueInstance, 'userName', userName);
        console.log('username:', userName)
      }, 2000);
    }
  }
});
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <span>{{ message }}</span><br>
  <span>`{{ userName }}´ (Output result of var userName here)</span><br>
  <button @click="getName">Click me and wait for 2 seconds, the username will be updated</button>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

That makes sense! Thanks for the detailed response.
1

To you can use {{ user.username }}, in your data you need put like that:

data(){
    return{
        user: { 
            username:  ' '
        }
    }
}

and you are not updating the right username instance, you can change this line:

var userName = snapshot.val().username;

for this:

this.username = snapshot.val().username;

1 Comment

Attempted this but receive the following error: TypeError: null is not an object (evaluating 'this.username = snapshot.val().username')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.