JSFiddle - React, Tailwind, and code Playground
by ChangJoo Park
HTML
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
{{focused}}
<item v-for="item in items" :key="item.id" :item="item" v-bind:hasFocus="item.id === focused" v-on:set-focus="setFocus"></item>
</div>
<template id="item">
<div class="item" v-bind:class="{ focus }" @click="focusItem">
<span>{{item.text}}</span>
</div>
</template>
CSS
.item {
width: 100px;
height: 100px;
display: inline-block;
background-color: white;
margin: 10px;
padding: 10px;
}
.item.focused {
background-color: tomato;
}
JavaScript
window.focusedIndex = 3;
Vue.component('item', {
props: ['item', 'has-focus'],
created: function () {
console.log(this.hasFocus)
},
template: '#item',
methods: {
focusItem: function() {
this.$emit('set-focus', this.item.id)
}
}
})
new Vue({
el: '#app',
created: function () {
this.focused = window.focusedIndex
},
data: function() {
return {
focused: 0,
items: [{
id: 1,
text: 'item 1'
}, {
id: 2,
text: 'item 2'
}, {
id: 3,
text: 'item 3'
}, {
id: 4,
text: 'item 4'
}, {
id: 5,
text: 'item 5'
}]
}
},
methods: {
setFocus: function (id) {
this.focused = id
}
}
})