2

New to vuejs, just trying to play around. I have an object with values that I want to post in my template.

export default {
    name: 'frontPage',
    data : function() {
        return {
            
        }
    },
    methods : {
        player () {
            this.lvl = 1;
            this.df = this.lvl * 1.3;
            this.hp = this.lvl * 100 / 3;
            this.ap = this.hp/10;
            this.name = 'Guest';
        }
    },
    
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<h2 id="name">   
    {{ player.name }}    
</h2>
<h2 id="lvl">   
    {{ player.lvl}}    
</h2>

1 Answer 1

3

First you need to initialize player into your data so you will be able to access it everywhere into the component, then proceed by using the Computed Properties to give the dom the calculated player fields and update the player data too, for reference take a look at this :

https://v2.vuejs.org/v2/guide/computed.html#Computed-Properties

For your code i did something like this:

new Vue({
  el: '#app',
  name: 'frontPage',
  data: function() {
    return {
      player: {
        lvl: 1,
        df: null,
        hp: null,
        ap: null,
        name: 'Guest'
      }
    }
  },
  computed: {
    // a computed getter
    showPlayer: function() {

      // `this` points to the vm instance
      this.player.df = this.player.lvl * 1.3
      this.player.hp = this.player.lvl * 100 / 3
      this.player.ap = this.player.hp / 10

      return this.player
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h2 id="name">
    {{ showPlayer.name }}
  </h2>
  <h2 id="df">
    {{ showPlayer.df}}
  </h2>
  <h2 id="hp">
    {{ showPlayer.hp}}
  </h2>
  <h2 id="ap">
    {{ showPlayer.ap}}
  </h2>
</div>

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

1 Comment

Been trying to figure this out since 3 days !

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.