VueJS renders variable twice in loop - vue.js

When I press some key in editable <li> it shows this content twice. Out of this v-for loop, it shows only once. So in this array is for example ['a'] but in <li> it shows 'aa'
new Vue({
el: '#app',
data: {
component: {
items: ['']
}
},
methods: {
onKeydown(e, index) {
if(e.key === 'Enter') {
e.preventDefault()
this.component.items.push('')
}
},
onInput(e, index, item) {
this.component.items.splice(index, 1, e.target.innerHTML)
}
}
});
<div id="app">
<ul>
<li contenteditable="true"
v-for="(item, index) in component.items"
:key="index"
#keydown="onKeydown($event, index)"
#input="onInput($event, index, item)"
>{{ item }}</li>
</ul>
{{ component.items }}
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Related

My page reloads, and the added task wont register

I am creating a to do list for my exam. For some reason the page keep reload when I click add task, and the tasks wont register. I am new to Vue.js and Javascript.
I have problems with finding the issue. It is a simple code, not to complex, but the add task part is not working.
Here is my code:
<template >
<section class="todolist">
<h1 class="title">{{ title }}</h1>
<form class="container">
<h3 class="container__title">New Task </h3>
<input class="container__input" type="text" placeholder="Enter task" v-model="task">
<button class="container__button" #click="addPlanningTask">Add Task</button>
<h3 class="container__title-second">To Do List</h3>
<ul>
<li v-for="(task, index) in tasks" :key="index">
<span>{{ task.name }} </span>
<button class="todolist__button" #click="deletePlanningTask">Remove</button>
</li>
</ul>
<h4 class="container__list-title" v-if="task.length === 0">
List is empty!</h4>
</form>
</section>
<div class="guestlist">
<h4 class="guestlist__title">{{ invited }}</h4>
<span>{{ guestList }}</span>
<button class="guestlist__button" #click="toggleGuestList">Guestlist</button>
<div v-if="isGuestListVisible === true">
<ul>
<li v-for="guest in people" :key="guest.id.value">
{{ guest.name.first }} {{ guest.name.last }}</li>
</ul>
</div>
</div>
</template>
export default {
props: {
titleName: {
type: String,
default: 'todolist',
},
},
data() {
return {
title: 'Planning the party!',
task: '',
tasks: [{
name: ''
}],
invited: 'Who is invited?',
guestList: '',
people: [],
name: '',
isGuestListVisible: false
}
},
created() {
this.addGuest();
},
methods: {
async addGuest() {
const url = 'https://randomuser.me/api/?page=2&results=8';
const res = await fetch(url);
const { results } = await res.json();
this.people = results;
},
toggleGuestList() {
this.isGuestListVisible = !this.isGuestListVisible;
},
addPlanningTask() {
if(this.task.length === 0)
return;
this.tasks.push({
name: this.task
});
},
deletePlanningTask(index) {
this.tasks.splice(index, 1);
},
},
};
</script>
You can use #submit.prevent on form if you don't want to reload page:
new Vue({
el: "#demo",
props: {
titleName: {
type: String,
default: 'todolist',
},
},
data() {
return {
title: 'Planning the party!',
task: '',
tasks: [],
invited: 'Who is invited?',
guestList: '',
people: [],
name: '',
isGuestListVisible: false
}
},
created() {
this.addGuest();
},
methods: {
async addGuest() {
const url = 'https://randomuser.me/api/?page=2&results=8';
const res = await fetch(url);
const { results } = await res.json();
this.people = results;
},
toggleGuestList() {
this.isGuestListVisible = !this.isGuestListVisible;
},
addPlanningTask() {
if (this.task.length === 0) return;
this.tasks.push({ name: this.task });
},
deletePlanningTask(index) {
this.tasks.splice(index, 1);
},
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo" >
<section class="todolist">
<h1 class="title">{{ title }}</h1>
<form class="container" #submit.prevent>
<h3 class="container__title">New Task </h3>
<input class="container__input" type="text" placeholder="Enter task" v-model="task">
<button class="container__button" #click="addPlanningTask">Add Task</button>
<h3 class="container__title-second">To Do List</h3>
<ul>
<li v-for="(task, index) in tasks" :key="index">
<span>{{ task.name }} </span>
<button class="todolist__button" #click="deletePlanningTask">Remove</button>
</li>
</ul>
<h4 class="container__list-title" v-if="task.length === 0">List is empty!</h4>
</form>
</section>
<div class="guestlist">
<h4 class="guestlist__title">{{ invited }}</h4>
<span>{{ guestList }}</span>
<button class="guestlist__button" #click="toggleGuestList">Guestlist</button>
<div v-if="isGuestListVisible === true">
<ul>
<li v-for="guest in people" :key="guest.id.value">
{{ guest.name.first }} {{ guest.name.last }}</li>
</ul>
</div>
</div>
</div>

Run a Vue function to fetch array data inside a v-for when a Bootstrap collapse is clicked

Good day forks. Please help. I want to Run a Vue function to fetch array data inside a v-for when a Bootstrap collapse is clicked. So I have an array of items with (id, title, description etc) attributes. Then for each of the item, it has an array of sub-items. So I want to fetch the sub-items when I click the item and shows in a bootstrap collapse div as follows:
<div v-for="item in items" :key="item.id">
<p>
<a :href="'#' + item.id" data-toggle="collapse">{{
item.item_name
}}</a>
</p>
<div class="collapse" :id="item.id">
<div v-html="getSubItems(item.id)">
<p v-for="sub_item in sub_items" :key="sub_item.id">
{{ sub_item.sub_item_name }}
</p>
</div>
<p>
<span class="glyphicon glyphicon-time"></span> 5:44 Status
<span class="label label-success pull-right">{{
item.item_status ? "Done" : "Pending"
}}</span>
</p>
</div>
<hr />
</div>
And the JavaScript is as follows:
export default {
props: {},
data() {
return {
id: 1,
items: [],
sub_items: []
};
},
created() {
axios
.get("http://ip/api/v1/items")
.then(response => {
console.log(response.data);
this.topics = response.data.data;
})
.catch(error => {
console.log(error);
});
},
methods: {
getSubItems: function(item_id) {
return axios
.get("http://ip/api/v1/sub-items/" + item_id)
.then(response => {
console.log(response.data);
this.sub_items = response.data.data;
})
.catch(error => {
console.log(error);
});
}
}
};
If I was you, I would respond to a click event on the anchor tag to get the sub_items.
v-html is used to render raw HTML which is probably why your code doesn't work.
I've created a snippet below (without the axios) to show one way you could get it working.
new Vue({
el: "#app",
data() {
return {
id: 1,
items: [],
sub_items: []
};
},
created() {
this.getItems();
},
methods: {
getItems: function() {
this.items = [{
id: 1,
item_name: "Test Item"
}];
},
getSubItems: function(item_id) {
this.sub_items = [{
id: 1,
sub_item_name: "Test Sub Item"
}];
}
}
});
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div id="app">
<div v-for="item in items" :key="item.id">
<p>
<a :href="'#panel-' + item.id" data-toggle="collapse" #click="getSubItems(item.id)" role="button" aria-expanded="false" aria-controls="collapseExample">{{
item.item_name
}}</a>
</p>
<div class="collapse" :id="'panel-' + item.id">
<div>
<p v-for="sub_item in sub_items" :key="sub_item.id">
{{ sub_item.sub_item_name }}
</p>
</div>
<p>
<span class="glyphicon glyphicon-time"></span> 5:44 Status
<span class="label label-success pull-right">{{
item.item_status ? "Done" : "Pending"
}}</span>
</p>
</div>
<hr />
</div>
</div>
Try this:
<a :href="'#' + item.id" data-toggle="collapse" #click="getSubItems(item)">{{
item.item_name
}}</a>
//
getSubItems: function(item) {
if (!item.subItems){
return axios
.get("http://ip/api/v1/sub-items/" + item_id)
.then(response => {
console.log(response.data);
this.sub_items = response.data.data;
})
.catch(error => {
console.log(error);
});
}
}
}
only fetch subitems if you don't already have. So you should make a check in the function if you have them.
The simplest way I think would be to save the results on the item itself as item.subItems then once you open you don't need to open again

vue.js - Dynamically render items on scroll when visible

I have list of 100+ items and rendering takes too much time. I want to show just the once that are visible, and rest on scroll.
What's the best approach?
I have this snippet below, but the vue.set() isn't working.
var dbItems = [{name: 'New item'}, {name:'Another'}, {name:'Third'}];
var app = new Vue({
el: '#app',
data: {
// if I put items : dbItems, then for some reason the Vue.set() doesn't work!!
items : [],
},
methods: {
init: function () {
this.items = dbItems; // we add all items
},
makeItemVisible : function(id) {
console.log("Making visible #"+id);
this.items[id].show = 1;
Vue.set(this.items, id, this.items[id]);
}
}
});
app.init();
app.makeItemVisible(1); // this works
$(document).on('scroll', function(){
// function to show elements when visible
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div id="app" v-cloak>
<button v-on:click="makeItemVisible(0)">MAKE VISIBLE - This button doesn't work</button>
<div class="items" v-show="items.length">
<!-- I dont know why, but (key, item) had to be switched compared to VUE documentation! -->
<div v-for="(key, item) in items">
<div v-if="item.show" style="border:2px solid green;height:700px">
You can see me: {{ item.name }} | ID: {{ key }}
</div>
<div class="item-blank" data-id="{{ key }}" v-else style="border:2px solid red;height:700px">
{{ item.name }} invisible {{ key }}
</div>
</div>
</div>
</div>
Solved.
Edit: This Vue.js is only useable in Chrome... otherwise it is incredibly slow (Firefox is slowest), it works better when loading the whole document in HTML at once.
var dbItems = [{name: 'New item'}, {name:'Another'}, {name:'Third'}];
var app = new Vue({
el: '#app',
data: {
items : dbItems
},
methods: {
makeItemVisible : function(id) {
console.log("Making visible #"+id);
Vue.set(this.items[id], 'show', 1);
}
}
});
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return (elemTop <= docViewBottom && elemTop >= docViewTop) || (elemBottom >= docViewTop && elemBottom <= docViewBottom);
}
var fn = function(){
$('.item-blank').each(function(){
if(isScrolledIntoView(this)) {
app.makeItemVisible($(this).attr('data-id'));
}
});
};
$(window).scroll(fn);
fn(); // because trigger() doesn't work
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app" v-cloak>
<div class="items" v-show="items.length">
<div v-for="(item, index) in items">
<div v-if="item.show" style="border:2px solid green;height:700px">
You can see me: {{ item.name }} | ID: {{ index }}
</div>
<div class="item-blank" :data-id="index" v-else style="border:2px solid red;height:700px;position:relative;">
{{ item.name }} invisible {{ index }}
</div>
</div>
</div>
</div>

how to use "v-for" for adding or removing a row with multiple components

i have a row with 3 components(in which is a defined component 1, component 2 and component 3, as showed in my previous question:
VueJs component undefined )
how can i add a row or remove a row (in which has 3 components) using v-for?
var data1={selected: null, items:["A", "B"]};
Vue.component('comp1', {
template: `<select v-model="selected">
<option disabled value="">Please select</option>
<option v-for="item in items" :value="item">{{item}}</option>
</select>`,
data:function(){
return data1
}
});
<!---similar for component 2 and 3--->
new Vue({
el: '#app',
data: {
rows:[]
},
methods:{
addRow: function(){
this.rows.push({});
},
removeRow: function(row){
//console.log(row);
this.rows.$remove(row);
}
},
});
in .html
<script src="https://unpkg.com/vue"></script>
<div id="app">
<div v-for ="row in rows">
<comp1></comp1>
<comp2></comp2>
<comp3></comp3>
<button #click="addRow">Add Row</button>
<button #click="removeRow(row)">Remove Row</button>
</div>
</div>
The code is pretty close. Try this.
console.clear()
const template = {
template: `<select v-model="selected">
<option disabled value="">Please select</option>
<option v-for="item in items" :value="item">{{item}}</option>
</select>`,
data: function() {
return {
selected: null,
items: ["A", "B"]
}
}
};
Vue.component("comp1", template)
Vue.component("comp2", template)
Vue.component("comp3", template)
new Vue({
el: '#app',
data: {
rows: []
},
computed:{
newId(){
return this.rows.length == 0 ? 1 : Math.max(...this.rows.map(r => r.id)) + 1
}
},
methods: {
addRow: function() {
this.rows.push({id: this.newId });
},
removeRow: function(row) {
this.rows.splice(this.rows.indexOf(row), 1)
}
},
});
<script src="https://unpkg.com/vue"></script>
<div id="app">
<div v-for="row in rows" :key="row.id">
<comp1></comp1>
<comp2></comp2>
<comp3></comp3>
<button #click="removeRow(row)">Remove Row</button>
</div>
<button #click="addRow">Add Row</button>
</div>
This code moves the add row button outside the loop, because you don't really need multiple add row buttons. Additionally, it adds a key for each div in the loop so that Vue can properly remove components when necessary. In order to generate the key, the code creates an id property for each new row object.

Vue alternate classes in v-for

I have an array (history) that is being pushed two items every time a button is pressed. Those two items will need to have different css styles when printed.
HTML
<ul class="info">
<li :class="{ 'style-one' : toggle, 'style-two' : toggle }" v-for="item in history">{{item}}</li>
</ul>
JS (Vue)
methods: {
attack: function() {
this.history.unshift(this.playerDamaged);
this.history.unshift(this.monsterDamaged);
}
The problem with this is there is no way to change the truthiness of toggle during the loop. Is there a better way to approach this?
SOLUTION 1 :
You can use this code :
<ul class="info">
<li v-for="item in history" :key="item"
:class="{ 'style-one' : item.isPlayer, 'style-two' : !item.isPlayer }"
>
{{ item.text }}
</li>
</ul>
methods: {
attack: function() {
this.history.unshift({ text: this.playerDamaged, isPlayer: true });
this.history.unshift({ text: this.monsterDamaged, isPlayer: false });
}
UPDATED - SOLUTION 2 [No use of objects] :
You can use an other solution with no objects :
<ul class="info">
<li v-for="(item, index) in history" :key="item"
:class="'style-' + ((index % numberOfPlayers) + 1)"
>
{{ item }}
</li>
</ul>
//This part don't have to deal with Array of Objects :
methods: {
attack: function() {
this.history.unshift( this.playerDamaged );
this.history.unshift( this.monsterDamaged );
},
computed: {
numberOfPlayers: function() {
return 2;
}
}
If you want to add a player (ex: monster 2) you have to update the computed numberOfPlayers to 3 (or better : listOfPlayers.length if you have) and create a class ".style-3".
Code example :
new Vue({
el: "#app",
data: function() {
return {
myArray: ['player attack', 'monster attack','player attack', 'monster attack']
}
},
computed: {
numberOfPlayers: function() {
return 2;
}
}
});
.style-1 {
color: blue;
}
.style-2 {
color: red;
}
<script src="https://vuejs.org/js/vue.min.js"></script>
<div id="app">
<div v-for="(item, index) in myArray" :key="item"
:class="'style-' + ((index % numberOfPlayers) + 1)"
>
{{ item }}
</div>
</div>