как разместить значения объекта в vuejs - PullRequest
2 голосов
/ 20 февраля 2020

Новичок в vuejs, просто пытаюсь поиграть. У меня есть объект со значениями, которые я хочу опубликовать в своем шаблоне.

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 Ответ

3 голосов
/ 20 февраля 2020

Сначала вам нужно инициализировать игрока в ваши данные, чтобы вы могли получить к нему доступ повсюду в компоненте, а затем продолжить, используя Computed Properties, чтобы предоставить dom рассчитанные поля игрока и обновить данные игрока тоже, для справки. посмотрите на это:

https://vuejs.org/v2/guide/computed.html#Computed -Свойства

Для вашего кода я сделал что-то вроде этого:

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...