Class and Style Attributes in Vue
by jessupjs
HTML
<h1>Class & Style Attributes in Vue, woo-hoo!</h1>
<p>Click the circle to witness some cool componetry</p>
<div id="circleApp">
<circles></circles>
</div>
CSS
* {
border: 0;
padding: 0;
margin: 0;
}
h1 {
font-size: 1.5rem;
padding: 0.25% 1%;
}
p {
font-style: italic;
padding: 0.25% 2%;
}
#circleApp {
align-items: center;
display: flex;
height: 175px;
justify-content: center;
margin: 1.25%;
position: relative;
width: 450px;
}
.circle {
border-radius: 50%;
position: absolute;
}
.lg {
height: 100px;
transition: 0.25s linear;
width: 100px;
}
.md {
height: 75px;
transition: 0.25s linear;
width: 75px;
}
.sm {
height: 50px;
transition: 0.5s linear;
width: 50px;
}
JavaScript
// Create new Vue component
Vue.component('circles', {
data: function() {
// Closure style
return {
// Class booleans
isLg: true,
isMd: false,
isSm: false,
// Style properties
position: {
left: '25%',
top: '25%',
backgroundColor: 'rgb(255, 0, 0)'
}
}
},
methods: {
// Toggle circle classes
toggleClass : function() {
// If .lg
if (this.isLg === true) {
this.isLg = false;
this.isMd = true;
this.isSm = false;
// Else if .md
} else if (this.isMd === true) {
this.isLg = false;
this.isMd = false;
this.isSm = true;
// Else (.sm)
} else {
this.isLg = true;
this.isMd = false;
this.isSm = false;
}
},
// Move circle randomly
randomMove : function() {
// Generate random numbers
var randomLeft = Math.random() * 100;
var randomTop = Math.random() * 100;
var randomR = Math.floor(Math.random() * 255)
var randomG = Math.floor(Math.random() * 255)
var randomB = Math.floor(Math.random() * 255)
// Install into position
this.position.left = `${randomLeft}%`;
this.position.top = `${randomTop}%`;
this.position.backgroundColor = `rgb(${randomR}, ${randomG}, ${randomB})`;
// Return position
return this.position;
},
// Combine functions for single click event
doItAll : function() {
this.toggleClass();
this.randomMove();
}
},
// <circles> modifies class and style
template:
'<div v-on:click="doItAll()" \
class="circle" v-bind:class="{ lg : isLg, md : isMd, sm : isSm }"\
v-bind:style="position">\
</div>'
});
// Initialize Vue app
var v = new Vue({
el: '#circleApp'
});