Vue.js - Event Listeners and v-on directive

by wistcc

HTML

<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
    <h3>Player List</h3>
    <ul>
      <li-comp v-for="player in players" v-bind:player="player"></li-comp>
    </ul>
    
    {{ totalPoints }}
    <add-points v-on:add-points="addPoints" />
</div>

JavaScript

Vue.component('li-comp', {
  props: ['player'],
  template: '<li>{{player.name}} has {{this.player.points[0]}} points.</li>',
});

Vue.component('add-points', {
	data: function(){
  	return {
    	points: 0
    }
  },
  template: `<div>
              <h4>Add points to all players</h4>
              <input v-model="points" />
              <button v-on:click="addPoints">Add points</button>
            </div>`,
  methods: {
  	addPoints() {
    	this.$emit('add-points', this.points);
      this.points = 0;
    },
  },
});

new Vue({
  el: '#app',
  data: {
    players: [
    	{
      	name: "Player 1",
        points: [5, 0]
      },
    	{
      	name: "Player 2",
        points: [8, 0]
      },
    	{
      	name: "Player 3",
        points: [10, 0]
      },
    ],
    isVisible: true,
  },
  computed: {
  	sortedPlayers() {
    	return this.players.sort((a, b) => b.name > a.name);
    },
    totalPoints() {
    	return this.sortedPlayers.reduce((total, current) => total + current.points[0], 0);
    },
  },
  watch: {
  	players() {
    	console.log('changed')
    },
  },
  methods: {
  	addPoints(points) {
    	this.players.forEach(player => {
      	player.points.splice(0, 1, player.points[0] + Number(points));
      })
    },
  },
})