example 07 practice vuejs Intro (angular-reactjs-vuejs-quickstart-comparison)
by hasandag
HTML
<script src="https://unpkg.com/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
<div id="app">
<p v-bind:style="{color: hobbies.length > 3 ? 'red' : 'black'}" v-bind:class="{'multiple-hobbies': hobbies.length > 3}">Hobbies: {{ hobbies.length }}</p>
<p v-if="deletedValue">Hobby Deleted!</p>
<input type="text" v-model="userInput">
<button v-on:click="addHobby">New Hobby</button>
<ul>
<app-hobby v-for="hby in hobbies" v-bind:hobby="hby" v-on:hbyclicked="removeHobby($event)"></app-hobby>
</ul>
</div>
<!--
1) Create a <div> and take control with a Vue Instance
2) Output an array of hobbies in this <div> (provide some default hobbies)
3) Add a 'New Hobby' button + <input> field where you add the hobby the user entered to the list
4) Make the hobbies clickable to remove them once clicked
5) Add a <p>Hobby deleted!</p> which is only shown once at least one hobby was deleted (be creative on how to track this!)
6) Add a hobby counter (<p>Hobbies: ...</p>) above the list of hobbies
7) Dynamically style/ add classes to the hobby counter, depending on whether you have more or less than 3 hobbies
8) Outsource your hobbies (the <li> elements) into a re-usable component
-->
CSS
.multiple-hobbies {
border: 1px solid red;
}
JavaScript
Vue.component('app-hobby', {
props: ['hobby'],
template: '<li v-on:click="hobbyClicked">{{ this.hobby.name }}</li>',
methods: {
hobbyClicked() {
this.$emit('hbyclicked', this.hobby);
}
}
});
new Vue({
el: '#app',
data: {
hobbies: [{
id: _.uniqueId(),
name: 'Dalma'
}, {
id: _.uniqueId(),
name: 'Batma'
}, {
id: _.uniqueId(),
name: 'Çıkma'
}],
userInput: "",
deletedValue: false
},
methods: {
addHobby: function() {
if (this.userInput.trim() == "") {
return;
}
var newId = _.uniqueId();
var newHobby = {
id: newId,
name: this.userInput,
value: newId
};
this.hobbies.push(newHobby);
this.userInput = "";
this.deletedValue = false;
console.log(this.hobbies);
},
removeHobby(hobby) {
var id = hobby.id;
for (i = 0; i < this.hobbies.length; i++) {
if (this.hobbies[i].id == id) {
this.deletedValue = true;
this.hobbies.splice(i, 1);
console.log(this.deletedValue);
break;
}
}
}
}
});