VueJS Select only one element in a v-for - javascript

I'm using Vue v2
I'm trying to change only the properties of the selected element. See, when the response is marked after the click, it should change to a red color with a text that says 'Unmark'. And vice versa: if the button is clicked again (which now would say 'Unmark'), it should change to a green color and the text would be 'Mark'. Alas, it works.... Nevertheless, my code applies the change to every element inside the v-for; I only want that to happen to the selected element.
I've thought about using a Component to check if somethings changes, but first I'd like to see if there's a solutions for this. ANy help will be appreciated
Here's my code:
<div class="search-results">
<div class="activity-box-w" v-for="user in users">
<div class="box">
<div class="avatar" :style="{ 'background-image': 'url(' + user.customer.profile_picture + ')' }">
</div>
<div class="info">
<div class="role">
#{{ '#' + user.username }}
</div>
<div>
<div>
<p class="title">#{{ user.customer.name }}
#{{user.customer.lastname}}
</p>
</div>
</div>
</div>
<div class="time">
<input type="button" class="btn btn-sm btn-primary" v-on:click.prevent="markUser(user)" v-model="text"
v-bind:class="[{'green-border':notMarked}, {'red-border':marked}]" v-cloak v-if="!action"
:disabled="action"></input>
</div>
</div>
</div>
Now for the script:
new Vue({
el: '#engage-panel',
data: {
users: [],
mark: {'id' : '', 'marks' : ''},
text: 'Mark', //Migth change to Unmark later on
action: false,
marked: null,
notMarked: null,
},
methods:
{
markUser: function(user){
this.mark.id = user.id;
this.action= true;
Vue.http.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content');
this.$http.put('/mark/user', this.mark).then(response => {
if(response.body === "marked")
{
this.mark.marks="true";
this.text = 'Unmark';
this.marked= true;
this.notMarked= false;
this.action= false;
}else{
this.mark.marks="false";
this.text = 'Mark';
this.marked= false;
this.notMarked= true;
this.action= false;
}
}).catch(e => {
this.action= false;
});
}
}

You can use $event.target on click if you just need to toggle css class.
fiddle here
But it's true that it's easier if a user has a status like marked = true/false for example, you just need to bind class like :
<input :class="{ 'green-border': user.marked, 'red-border': !user.marked }">

The issue my code applies the change to every element you met is caused by every user in v-for="user in users" uses one same object to indicates it is marked or not.
If your users data has one property like status to save current status (like unmark, mark etc), it is very simple, just change to next status when click mark button.
If your users data doesn't have that property, you need to create one dictionary, then save the users already clicked as key, the status for the user will be the value.
Below is one demo:
app = new Vue({
el: "#app",
data: {
users1: [{'name':'abc', 'status':'none'},
{'name':'xyz', 'status':'none'}],
users2: [{'name':'abc'}, {'name':'xyz'}],
selectedUsers: {}
},
methods: {
getNextStatusBaseOnRoute: function (status) {
if(status ==='marked') return 'marked'
let routes = {'none':'unmark', 'unmark':'marked'}
return routes[status]
},
markUser1: function (item) {
item.status = this.getNextStatusBaseOnRoute(item.status)
},
markUser2: function (item) {
let status = item.name in this.selectedUsers ? this.selectedUsers[item.name] : 'none'
// remember to use vue.$set when adding new property to one object
this.$set(this.selectedUsers, item.name, this.getNextStatusBaseOnRoute(status))
}
}
})
.marked {
background-color:green;
}
.unmark {
background-color:yellow;
}
<script src="https://unpkg.com/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<h2>Case 1: </h2>
<div v-for="(item, index1) in users1" :key="'1'+index1">
<span>{{item.name}}:</span><span :class="[item.status]">{{item.status}}</span><button #click="markUser1(item)">Mark</button>
</div>
<h2>Case 2: </h2>
<div v-for="(item, index2) in users2" :key="'2'+index2">
<span>{{item.name}}:</span><span :class="[item.name in selectedUsers ? selectedUsers[item.name] : 'none']">{{item.name in selectedUsers ? selectedUsers[item.name] : 'none'}}</span><button #click="markUser2(item)">Mark</button>
</div>
</div>

For Vue3, you can also store the index of the selected element
<ul role="list" class="">
<li class="relative" v-for="(image, index) of images" :class="selectedImage == index? 'border-indigo-500 border-2': 'border-transparent'" >
<div #click="selectedImage = index" class="">
<img :src="image" alt="" class="object-cover pointer-events-none group-hover:opacity-75">
</div>
</li>
</ul>

Related

Using target.event how to close the dropdown when clicked outside in Vuejs?

const app = new Vue({
el: "#app",
name: 'aselect',
data: {
value: 'Select a Fruit',
list: ["Orange", "Apple", "Kiwi", "Lemon", "Pineapple"],
visible: false
},
methods: {
toggle() {
this.visible = !this.visible;
},
select(option) {
this.value = option;
}
}
})
<div id="app">
<h1>Custom Select Dropdown</h1>
<div class="aselect" :data-value="value" :data-list="list">
<div class="selector" #click="toggle()">
<div class="label">
<span>{{ value }}</span>
</div>
<div class="arrow" :class="{ expanded : visible }"></div>
<div :class="{ hidden : !visible, visible }">
<ul>
<li :class="{ current : item === value }" v-for="item in list" #click="select(item)">{{ item }}</li>
</ul>
</div>
</div>
</div>
</div>
I am using the reference from https://www.npmjs.com/package/vue-click-outside
This is my codepen link https://codepen.io/santoshch/pen/gOmvvmN In the codepen link, i have a dropdown, where after toggling down the dropdown i am unable to close the dropdown list.
So i have searched for some reference i vuejs, And finally found npm package called vue-click-outside, Itried to place event but not sure how to proceed.
I found out a solution to your problem. Follow below steps
At first Add box class to every element that lies inside the box that toggle the dropdown
<div id="app">
<h1>Custom Select Dropdown</h1>
<div class="aselect" :data-value="value" :data-list="list">
<div class="selector box" #click="toggle()">
<div class="label box">
<span class="box">{{ value }}</span>
</div>
<div class="arrow box" :class="{ expanded : visible }"></div>
<div :class="{ hidden : !visible, visible }">
<ul>
<li :class="{ current : item === value }" v-for="item in list" #click="select(item)">{{ item }}</li>
</ul>
</div>
</div>
</div>
</div>
Then add click listener to window in vue.js
const app = new Vue({
el: "#app",
name: 'aselect',
data: {
value: 'Select a Fruit',
list: ["Orange","Apple","Kiwi", "Lemon", "Pineapple"],
visible: false
},
methods: {
toggle() {
this.visible = !this.visible;
},
select(option) {
this.value = option;
},
handleClick(e){
const classname = e.target.className;
if(this.visible && !classname.includes("box")){
this.visible = false;
}
}
},
created () {
window.addEventListener('click', this.handleClick);
},
destroyed () {
window.removeEventListener('click', this.handleClick);
},
})
Check this pen: https://codepen.io/salim-hosen/pen/xxqYYMQ

How to filter an Array with Checkboxes items?

I want to filter my checkboxes I search it on internet there was information but I couldn't work it with my code.
This is the webpage
I want when you click on the checkbox it must be same as the category.
This is some code of the checkbox:
<div>
<input class="form-check-input checkboxMargin" type="checkbox" value="All" v-model="selectedCategory">
<p class="form-check-label checkboxMargin">All</p>
</div>
This is my grey box layout:
<div class="col-sm-12 col-md-7">
<div class="card rounded-circle mt-5" v-for="item of items" :key="item['.key']">
<div>
<div class="card-body defaultGrey">
<h5 class="card-title font-weight-bold">{{ item.name }}</h5>
<div class="row mb-2">
<div class="col-sm ">
<div class="row ml-0"><h6 class="font-weight-bold">Job:</h6><h6 class="ml-1">{{ item.job }}</h6></div>
<div class="row ml-0"><h6 class="font-weight-bold">Category:</h6><h6 class="ml-1">{{ item.categories }}</h6></div>
<div class="row ml-0"><h6 class="font-weight-bold">Location:</h6><h6 class="ml-1">{{ item.location }}</h6></div>
<div class="row ml-0"><h6 class="font-weight-bold">Niveau:</h6><h6 class="ml-1">{{ item.niveau }}</h6></div>
<div class="row ml-0"><h6 class="font-weight-bold">Availability:</h6><h6 class="ml-1">{{ item.availability }}</h6></div>
<h6>{{ item.info }}</h6>
<div class="row ml-0"><h6 class="font-weight-bold">Posted:</h6><h6 class="ml-1">{{ item.user }}</h6></div>
</div>
</div>
<div class="row">
<div class="col-xs-1 ml-3" v-if="isLoggedIn">
<router-link :to="{ name: 'InternshipDetails', params: {id: item['.key']} }" class="btn bg-info editbtn">
Details
</router-link>
</div>
<div class="col-xs-1 ml-3 mr-3" v-if="isLoggedIn && item.user == currentUser">
<router-link :to="{ name: 'Edit', params: {id: item['.key']} }" class="btn btn-warning editbtn">
Edit
</router-link>
</div>
<div class="col-xs-1" v-if="isLoggedIn && item.user == currentUser">
<button #click="deleteItem(item['.key'])" class="btn btn-danger dltbtn">Delete</button>
</div>
</div>
</div>
</div>
</div>
</div>
And I have my object here but how can I filter my grey boxes with category:
selectedCategory: []
Use computed properties:
computed: {
filteredItems(){
if(this.selectedCategory.length == 0) return this.items;
return this.items.filter(el => {
for(let i = 0; i < this.selectedCategory.length; i++){
if(el.categories == this.selectedCategory[i]) return el;
}
});
}
}
Then you go for v-for="item of filteredItems"
I didnt tested it. If you provide me more code i could help you more
You need to create one-way binding between your CategoryCheckBox component and your ListCard component.
Because you provided separated code when I can not reproduce it to give you a solution based on your own, I suggest this example to explain my solution.
Step One:
You have many ways to CRUD your items using a Plugins or Vuex or global instance, in my example I used global instance in main.js
Vue.prototype.$myArray = ["Books", "Magazines", "Newspaper"];
I assume you created your items data in the ListCards component
Step Two:
You need to add #change event in your checkbox to handle checked and unchecked states. I used static data (Book) for value.
<label>
<input type="checkbox" value="Books" #change="handleCategory($event)" /> Books
Now, let's implement handleCategory method, but before that, as we know that Checkbox and ListCards are independents which means we need to define a bus to create event communication between them and this is your issue so we define the bus inside the main.js
Vue.prototype.$bus = new Vue({});
Now we define handleCategory like this :
methods: {
handleCategory(e) {
this.$bus.$emit("checkCategory", e);
}
}
Step Three:
How can our ListCards listen to this event ?
By call $bus.$on(..) when the component is created ( Hope you know what Vue lifecycle methods mean )
created() {
this.$bus.$on("checkCategory", e => this.checkCategory(e));
},
When the user click the check box the component runs handleCategory then runs checkCategory inside ListCard.
Inside my ListCard, I have categories and originalCategories as data
data() {
return {
categories: this.$myArray,
originalCategories: this.$myArray
};
},
and a template :
<ul v-for="(category,index) in categories" :key="index">
<CategoryItem :categoryName="category" />
</ul>
and a created method ( lifecycle )
created() {
// $bus is a global object to communicate between components
this.$bus.$on("checkCategory", e => this.checkCategory(e));
},
and our filtering methods :
methods: {
checkCategory(e) {
let target = e.target;
let value = e.target.value;
target.checked
? this.filterCatergories(value)
: (this.categories = this.originalCategories);
},
filterCatergories(value) {
this.categories = this.categories.filter(val => val === value);
}
}
What's important for you is :
this.categories.filter(val => val === value); //will not do nothing
const categories=this.categories.filter(val => val === value); //will update the view.
And you can change the code or make it better and simple.
#Update
You can also use computed properties but because we have a parameter here which is the category name we need get and set.
computed: {
filteredItems: {
get: function() {
if (this.selectedCategory.length == 0) return this.items;
return this.items.filter(value => {
for (const category of this.selectedCategory) {
if (value == category) return value;
}
});
},
set: function(category) {
this.selectedCategory.push(category);
}
}
},
methods: {
checkCategory(e) {
let target = e.target;
let value = e.target.value;
target.checked
? (this.filteredItems = value)
: this.selectedCategory.pop(value);
}
}

Vue active class v-for

I have a question about v-for. Why do I have to return this.activeClass = {...this.activeClass} to update the component? Why component didn't update after this line.
if (this.activeClass[index]) {
this.activeClass[index] = false;
} else {
this.activeClass[index] = true;
}
I want set background to red on click on v-for element
Template:
<template>
<div class="container">
<div class="row mt-5">
<div
v-for="(quote, i) in quotes"
:key="i"
#click="del(i)"
:class="{red: activeClass[i]}"
class="quote col-3"
>
{{ quote }}
</div>
</div>
</div>
</template>
Script:
<script>
export default {
props: ["quotes"],
data: function() {
return {
activeClass: {}
};
},
methods: {
del(index) {
if (this.activeClass[index]) {
this.activeClass[index] = false;
} else {
this.activeClass[index] = true;
}
this.activeClass = {...this.activeClass};
}
}
};
</script>
Vuejs is not reactive on deep object. look at https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats
In addition to what the others have said, I can't help but feel that you're over-complicating this slightly. You're already looping over an object (quotes), why not apply an active property to those instead?
HTML
<div
v-for="(quote, i) in quotes"
:key="i"
#click="del(quote)"
:class="{active: quote.active}"
class="quote col-3"
>
{{ quote }}
</div>
Method Change
del(quote) {
quote.active = !quote.active;
}
New CSS
.quote.active{
background-color: red;
}

Vue.js toggling expanding v-for component from parent

I've got an 'Album' component that is being used on a page. I am trying to create something whereby only one album can be toggled at a given time. So if an album is already open when clicking another it would close.
Component being mounted recursively in the 'parent' app.
<album v-for="(album, index) in albums"
:key="index"
#expand="setAlbumContainerHeight"
#action="removeFromCollection"
:albumDetails="album"
page="collection">
</album>
The component itself.
<template>
<div v-on:click="toggleExpand" ref="album" class="album">
<img class="album-artwork" alt="album-artwork" :src="albumDetails.cover_url">
<div ref="expandContent" class="expanded-content">
<div class="left-block">
<div class="title">{{ albumDetails.title }}</div>
<div class="artist">{{ albumDetails.artist }}</div>
<!-- Search page specific -->
<div v-if="page === 'search'" class="info">{{ albumDetails.year }}<br> <span v-for="genre in albumDetails.genre"> {{ genre }}</span><br> {{ albumDetails.label }}</div>
<!-- Collection page specific -->
<div v-if="page === 'collection'" class="info">{{ albumDetails.year }}<br> <span v-for="genre in albumDetails.genres"> {{ genre.genre }}</span><br> {{ albumDetails.label }}</div>
<!-- Search page specific -->
<button v-if="page === 'search'" v-on:click.stop="addToCollection" class="add-collection">Add to collection</button>
<!-- Collection page specific -->
<button v-if="page === 'collection'" v-on:click.stop="removeFromCollection" class="add-collection">Remove from collection</button>
</div>
<div v-if="page === 'search'" class="right-block">
<div class="a-side">
<p v-for="track in albumDetails.track_list_one" class="track">{{ track }}</p>
</div>
<div class="b-side">
<p v-for="track in albumDetails.track_list_two" class="track">{{ track }}</p>
</div>
</div>
<div v-if="page === 'collection'" class="right-block">
<div class="a-side">
<p v-for="track in trackListOne" class="track">{{ track.track }}</p>
</div>
<div class="b-side">
<p v-for="track in trackListTwo" class="track">{{ track.track }}</p>
</div>
</div>
<img class="faded-album-artwork" alt="faded-album-artwork" :src="albumDetails.cover_url">
</div>
</div>
</template>
<script>
module.exports = {
name: 'Album',
props: ['albumDetails', 'page'],
data: function () {
return {
expanded: false,
expandedContentHeight: 0,
trackListOne: [],
trackListTwo: []
}
},
mounted() {
if (this.albumDetails.tracks) {
this.getTrackListOne(this.albumDetails.tracks);
this.getTrackListTwo(this.albumDetails.tracks);
}
},
methods: {
toggleExpand() {
if (!this.expanded) {
this.expanded = true;
this.$refs.expandContent.style.display = 'flex';
this.expandedContentHeight = this.$refs.expandContent.clientHeight;
let height = this.$refs.album.clientHeight + this.expandedContentHeight;
this.$emit('expand', height, event);
} else {
this.expanded = false;
this.$refs.expandContent.style.display = 'none';
let height = 'initial';
this.$emit('expand', height, event);
}
},
addToCollection() {
this.$emit('action', this.albumDetails.cat_no);
},
removeFromCollection() {
this.$emit('action', this.albumDetails.cat_no);
},
getTrackListOne(tracks) {
let halfWayThough = Math.floor(tracks.length / 2);
this.trackListOne = tracks.slice(0, halfWayThough);
},
getTrackListTwo(tracks) {
let halfWayThough = Math.floor(tracks.length / 2);
this.trackListTwo = tracks.slice(halfWayThough, tracks.length);
},
},
}
</script>
<style scoped lang="scss">
#import './styles/album';
</style>
The component itself is storing its state with a simple 'expanded' data attribute. Currently this means that the component works nicely when a user is opening and closing each album, however, problems occur when they are opening several at a time. Due to absolute positioning I am manually having to set the height of the container. The aim is to have only one open at a time. I am having trouble thinking of a way to store and track what album is currently open - I'm also unsure how the parent can manage the stage each album / open and closing them where. Even if I know which album is open in the parent how can I trigger individual child components methods?
I've tried to be as clear as possible, please let me know if there's anything else I can make clearer.
I'm not quite sure what you mean by recursive, as far as I can see you're not referencing the album component within itself recursively.
I'd go with this approach:
expanded is a property of your component.
On a click the component emits a this.$emit('expand', albumID).
In your parent you listen for the #expand event and assign your expandedAlbumID to the event payload.
The last remaining piece of the puzzle is now to pass your expanded property like :expanded="expandedAlbumID == album.id"
Full working example: https://codesandbox.io/s/o5p4p45m9

Toggle Class for an item Vue.js

So I have a list of data brought in using vue resource from an api. I'm trying to integrate this list with bootstrap accordion.
So:
I have set this :
data: {
taller: false
}
and
<div class="panel panel-default"
v-repeat="faq: faqs | filterBy searchText"
v-transition="staggered"
stagger="200"
v-on="click: toggleHeight"
v-class="active: taller">
So on click i'll call toggleHeight and pass through the faq instance :
toggleHeight: function(faq) {
this.taller = true;
}
This function sets to taller to true however it sets it to true for all faq items, not just the one i've passed to toggle height.
How can I only return taller: true for clicked faq item?
Thanks
<div id="demo">
<div class="input-group">
<input class="form-control" v-model="searchText">
</div>
<script id="item-template" type="x-template">
<div
class="stag"
v-on="click: toggleHeight()"
v-class="active: taller"
>
<h3>{{ item.question }}</h3>
<h4>{{ item.answer }}</h4>
</div>
</script>
<question
v-repeat="item: items | filterBy searchText"
v-transition="staggered"
stagger="200">
</question>
</div>
</div>
and the js:
Vue.component('question', {
template: document.querySelector('#item-template'),
data: function() {
return {
taller: false
}
},
methods: {
toggleHeight: function() {
this.taller = ! this.taller
}
}
});
new Vue({
el: '#demo',
ready: function() {
this.fetchItems();
},
methods: {
fetchItems: function() {
this.$http.get('/dev/frequently-asked-questions/api/index', function(items) {
this.$set('items', items);
});
}
}
});
Had to make use of components to target each item more directly.
First of all, you only have one variable taller. Not one per faq. So you'd have to change it a bit to something like this:
new Vue({
el: '#faq-list',
data: {
faqs: [{id:'foo',taller:false},{id:'bar',taller:true}]
},
methods: {
toggleHeight: function (faq, ev) {
faq.taller = false;
ev.target.classList.add('active');
}
}
});
And your HTML to something like this:
<div id="faq-list">
<div class="panel panel-default"
v-repeat="faq: faqs"
v-on="click: toggleHeight (faq, $event)"
v-class="active: taller">
{{ faq.id }}</div>
</div>
And for fun, I added CSS to see things working:
.active {
color: red;
}
Here's the JSfiddle, for your reference and to mess around with it. Click on one of the items in the list and it turns red.

Categories