Task Description:
Create a div-element and take control over it using a Vue-Instance.
Print an array of hobbies into the div-element. Provide some default hobbies.
Add a 'New Hobby' button and a text-input element. So that the user can add additional hobbies.
When a hobby list-item is clicked, it shall be removed from the list.
Add a "Hobby deleted"-paragraph which is only shown when a hobby-item has been deleted at least one time.
Above the list of hobbies add a hobby-counter which shows the current count of hobby-items.
Style the hobby-list depending on whether you have more or less then 3 hobbies in the list.
Outsource your hobbies (the list-item elements) into a component (so that it becomes re-usable).
Here's my solution for the points 1 to 7:
new Vue({
el: '#app',
data: {
hobbies: [{
name: 'Running'
},
{
name: 'Chess'
},
{
name: 'Cooking'
},
{
name: 'Hiking'
}
],
newHobby: '',
deleted: false
},
methods: {
addHobby: function() {
this.hobbies.push({
name: this.newHobby
});
},
removeHobby: function(event) {
let updatedHobbies = this.hobbies.filter((hobby) => {
return hobby.name !== event.target.textContent.trim();
});
this.hobbies = updatedHobbies;
if (!this.deleted) {
this.deleted = true;
}
},
setStyle: function() {
if (this.hobbies.length < 3) {
return 'pink';
} else if (this.hobbies.length === 3) {
return 'orange';
} else {
return 'cyan';
}
}
}
});
#app {
max-width: 800px;
margin: 0 auto;
}
li {
margin: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
<div id="hobby-counter">
<p>Hobbies: {{ hobbies.length }}</p>
</div>
<div id="add-control">
<input type="text" id="newHobby" v-model="newHobby" />
<button v-on:click="addHobby" id="addNewHobby">Add New Hobby</button>
</div>
<div id="deleted-message">
<p v-if="deleted">Hobby deleted!</p>
</div>
<li v-for="hobby in hobbies" v-on:click="removeHobby" v-bind:style="{ backgroundColor: setStyle() }">
{{ hobby.name }}
</li>
</div>
Is everything done in a good way and manner?
Where could my implementation been improved?
Any ideas how to solve point 8?
There I get finally stucked.
Looking forward to read your comments and answers.
Any ideas how to solve point 8?
- that sounds like a request for advice about code not written. Please refer to this post for more information regarding such requests - I would suggest you not ask that question, or this post may be closed as off-topic. \$\endgroup\$