This was my first experiment with Vue.js. I wanted to see how hard it would be to use one custom component inside another. Since this was a toy example, I decided to try to draw a chess board.
In line 39, I had to cast a string as a number. I’m sure there’s a better way to do that, but I’m not sure what it is yet. I also needed to specify a :key
attribute so that each element had a unique key… unfortunately, my key i+j
is not unique. I should have specified i*Number(size)+j
, but Vue.js did not complain, and this didn’t cause any bugs this time, so… ship it.
<html> <head> <title>Example Component</title> </head> <body> <p>Chess Board</p> <div id="app"> <board size=8></board> </div> <script src="https://unpkg.com/vue"></script> <script> Vue.component('square', { template: '<span :style="style"></span>', props: ['row', 'col'], methods: { getColor() { if ((Number(this.row) + Number(this.col)) % 2 == 0) { return 'white'; } else { return 'black'; } } }, computed: { style() { return { backgroundColor: this.getColor(), width: '50px', height: '50px', display: 'inline-block', border: 'solid black 1px', marginRight: '0px', marginTop: '-3px' }; } } }); Vue.component('board', { template: '<div><div v-for="i in Number(size)"><square v-for="j in Number(size)" :row=i :col=j :key=i+j></square></div></div>', props: ['size'] }); new Vue({ el: "#app", }); </script> </body> </html>