Changing class on radio button change - vue.js

My first column (Test1) is active, so the background turns orange. Why does the active class not change to the second column (Test2) when I click the radio button?
I'd like it to change the active class when the radio button is clicked.
I have the following template:
<template v-if="columns" v-for="(item, index) in columns" v-bind="item">
<div class="card-container"
:style="{'height': item.height+'%'}"
:class="{ active: item.active}">
<div class="card-inner">
<input type="radio" v-if="item.selectedDefault" checked v-model="currentInput" name="cardRadioGroup"
:value="item.id" v-on:change="updateDetails(item, index)"/>
<input type="radio" v-else v-model="currentInput" name="cardRadioGroup" :value="item.id"
v-on:change="updateDetails(item, index)"/>
<template v-if="item.gbAmount === null">
Onbeperkt
</template>
<template v-else>
{{ item.gbAmount }} GB
</template>
{{ currentInput }}
</div>
</div>
</template>
With the following Vue code:
import {onMounted} from "vue";
export default {
name: 'Card',
components: {Details},
data() {
const columns =
{
"Test1": {
"id": 1,
"gbAmount": 0,
"price": 5,
"selectedDefault": false,
"informationGet": ["bla", "bla"],
"informationUsing": "Boop.",
"recommended": false,
"height": 16.66,
"active": true,
},
"Test2": {
"id": 2,
"gbAmount": 1,
"price": 10,
"selectedDefault": false,
"informationGet": ["beh", "beh"],
"informationUsing": "Beep",
"recommended": false,
"height": 33.33,
"active": false,
},
}
return {
columns,
currentColumn: {},
checkedCard: [],
currentInput: null,
};
},
methods: {
updateDetails(item, index) {
this.currentColumn = {
...item,
name: index,
active: true,
}
console.log($(this.currentColumn));
},
},
setup() {
return {};
},
};
And CSS:
.active {
background: orange;
}

You update this.currentColumn but in template use this.columns. Correct will be:
updateDetails(item, index) {
Object.keys(this.columns).forEach(key => this.columns[key].active = false);
this.columns[index].active = true;
console.log(this.columns);
}

<template>
<div v-for="column in columns" :key="column.id">
<div
class="card-container"
:style="{ height: column.height + '%' }"
:class="{ active: column.id === currentInput }"
>
<div class="card-inner">
<input
type="radio"
name="cardRadioGroup"
:value="column.id"
v-model="currentInput"
/>
<template v-if="column.gbAmount === null"> Onbeperkt </template>
<template v-else> {{ column.gbAmount }} GB </template>
{{ currentInput }}
</div>
</div>
</div>
</template>
<script lang="ts">
import { ref } from 'vue'
const columns = [
{
id: 1,
gbAmount: 0,
price: 5,
selectedDefault: false,
informationGet: ['bla', 'bla'],
informationUsing: 'Boop.',
recommended: false,
height: 16.66,
},
{
id: 2,
gbAmount: 1,
price: 10,
selectedDefault: false,
informationGet: ['beh', 'beh'],
informationUsing: 'Beep',
recommended: false,
height: 33.33,
},
]
export default {
name: 'Card',
setup() {
const currentInput = ref(columns[0].id)
return {
columns,
currentInput,
}
},
}
</script>

Related

How to customize v-select in vue 2, options with icons or images

How to customize a select or another component like this design. I tried with v-select, BFormSelect, and others, the options are images or icons, and the output-
{
languages: {
en: {
title: "the text writted",
},
},
logo: "this logo in base64"
}
<template>
<div>
<div>
<b-form
ref="form"
class="repeater-form p-2"
#submit.prevent="repeateAgain"
>
<div>
<v-select
v-model="selected"
:options="options"
:multiple="false"
item-text="text"
item-value="value"
label="Select options"
>
<template slot="option" slot-scope="option">
<img :src="option.src" class="mr-2" style="width: 20px; height: 20px;"/>
{{ option.text }}
</template>
</v-select>
</div>
</b-form>
</div>
</div>
</template>
<script>
import {
BForm, BFormGroup, BFormInput, BRow, BCol, BButton, BFormCheckbox, BFormSelect, BDropdown
} from 'bootstrap-vue'
import vSelect from 'vue-select'
export default {
components: {
BForm,
BRow,
BCol,
BButton,
BFormGroup,
BFormInput,
BFormCheckbox,
BFormSelect,
vSelect,
BDropdown,
},
data() {
const typeOptions = ['include', 'not_include', 'important']
return {
typeOptions,
selected: [],
options: [
{
value: null,
text: "Please select some item",
src: ""
{
value: "b",
text: "Default Selected Option",
src: "../../../../assets/images/trip_icons/almuerzo.png"
},
{
value: "c",
text: "This is another option",
src: "../../../../assets/images/trip_icons/almuerzo.png"
},
{
value: "d",
text: "This one is disabled",
disabled: true,
src: "https://mdn.mozillademos.org/files/7693/catfront.png"
}
]
}
},
methods: {
select(option) {
console.log(option);
this.selected = option;
},
},
}
</script>
This is the result now but it is not enough, I hope to customize more.

Is it possible to make v-for variables dynamic in vue?

<div class="col-3" v-for="n in 5" :key="n">
<h3>Table {{n}}</h3>
<draggable class="list-group" :list="`list${n}`" group="people" #change="log">
<div
class="list-group-item"
v-for="`(element, index) in list${n}`"
:key="element.name"
>
{{ element.name }} {{ index }}
</div>
</draggable>
</div>
Why can't I set the v-for or :list as a concatenated string? Is there any way around this?
Full code:
<template>
<div class="row">
<component
v-for="(component, index) in components"
:key="index"
:is="component"
/>
<div class="col-3" v-for="n in listNumber" :key="n">
<h3>Table {{n}}</h3>
<draggable class="list-group" :list="list${n}" group="people" #change="log">
<div
class="list-group-item"
v-for="(element, index) in list${n}"
:key="element.name"
>
{{ element.name }} {{ index }}
</div>
</draggable>
</div>
</div>
</template>
<script>
import draggable from "vuedraggable";
let id = 1;
export default {
name: "two-lists",
display: "Two Lists",
order: 1,
components: {
draggable,
list:[],
},
data() {
return {
list1: [
{ name: "John", id: 1 },
{ name: "Joao", id: 2 },
{ name: "Jean", id: 3 },
{ name: "Gerard", id: 4 }
]
},
{
list2: [
{ name: "Juan", id: 5 },
{ name: "Edgard", id: 6 },
{ name: "Johnson", id: 7 }
],
listNumber: 3,
}
},
created(){
console.log(this.list);
},
methods: {
add: function() {
this.list.push({ name: "Juan" });
},
replace: function() {
this.list = [{ name: "Edgard" }];
},
clone: function(el) {
return {
name: el.name + " cloned"
};
},
}
};
</script>
It's a bit difficult to understand exactly what you're trying to do but it looks like you're trying to get a specific list in the v-for loop.
One way to fix your issue would be to nest your lists inside of an object in your data like this:
data() {
return {
listNumber: 3,
lists: {
list1: [
{ name: "John", id: 1 },
{ name: "Joao", id: 2 },
{ name: "Jean", id: 3 },
{ name: "Gerard", id: 4 }
],
list2: [
{ name: "Juan", id: 5 },
{ name: "Edgard", id: 6 },
{ name: "Johnson", id: 7 }
],
},
};
And then in your code you can just do lists[`list${n}`] like this:
<div class="col-3" v-for="n in listNumber" :key="n">
<h3>Table {{n}}</h3>
<draggable class="list-group" :list="lists[`list${n}`]" group="people" #change="log">
<div
class="list-group-item"
v-for="(element, index) in lists[`list${n}`]"
:key="element.name"
>
{{ element.name }} {{ index }}
</div>
There is a lot more refactoring and other cleanup you could (and should) probably do but this should at least get you over this hurdle.

How do i get the v-model values of a v-for components if i iterate with only numbers?

I have v-for form-group components i iterated over a select's value(integer). I want to get the values of the iterated v-models, but i just can't seem to get it right
TEMPLATE
<b-form-group
id="input-group-1"
label="Jumlah Lowongan:"
label-for="selectJumlahLow"
description="Silahkan pilih satu."
v-if="show"
>
<b-form-select id="selectJumlahLow" v-model="form.jumlahlow" :options="selow" required></b-form-select>
</b-form-group>
<b-form-group label="Nama Lowongan:" v-for="n in parseInt(form.jumlahlow)" :key="n">
<b-form-input required placeholder="Masukkan nama lowongan" v-model="low"></b-form-input>
</b-form-group>
SCRIPT DATA
data() {
return {
form: {
jumlahlow: 1,
checked: [],
low: []
}
}
I've tried changing the model to low[n] or declaring low in data as object {} but either of these seems to be undefined according to TypeErrors i've encoutered.
How am i suppose to get the low[n]'s values?
EDIT:
Here is the full code:
<template>
<div>
<b-form #submit="onSubmit" #reset="onReset">
<b-form-group
id="input-group-1"
label="Jumlah Lowongan:"
label-for="selectJumlahLow"
description="Silahkan pilih satu."
v-if="show"
>
<b-form-select id="selectJumlahLow" v-model="form.jumlahlow" :options="selow" required></b-form-select>
</b-form-group>
<b-form-group label="Nama Lowongan:" v-for="n in parseInt(form.jumlahlow)" :key="n">
<b-form-input required placeholder="Masukkan nama lowongan" v-model="low"></b-form-input>
</b-form-group>
<b-button type="submit" variant="primary">
{{ buttonText }}
<i class="material-icons">arrow_forward_ios</i>
</b-button>
<b-button type="reset" variant="danger">Reset</b-button>
</b-form>
<b-card class="mt-3" header="Form Data Result">
<pre class="m-0">{{ form }}</pre>
</b-card>
</div>
</template>
<script>
export default {
name: "lowonganForm",
data() {
return {
form: {
jumlahlow: 1,
checked: [],
low: []
},
selow: [
{ text: "Pilih Satu", value: null, disabled: true },
1,
2,
3,
4,
5,
6
],
show: true,
target: false,
buttonText: "Next"
};
},
methods: {
onSubmit(evt) {
evt.preventDefault();
alert(JSON.stringify(this.form));
// if (this.jumlahlow !== null || !this.jumlahlow < 1) {
// this.show = false;
// }
},
onReset(evt) {
evt.preventDefault();
// Reset our form values
this.form.jumlahlow = null;
this.form.checked = [];
// Trick to reset/clear native browser form validation state
this.show = false;
this.$nextTick(() => {
this.show = true;
});
}
},
computed: {}
};
</script>
You should try to model your data for how you want the view to be rendered. If you want to have a list of input boxes, then the data for those inputs should be defined in an array that is prepopulated with those items, or when you need to adjust the number of items you should add those data items to the array. You'll avoid reactivity problems this way too.
Here's an example of what I mean:
new Vue({
el: '#app',
data: {
maxCount: 5,
count: 3,
items: [],
data: '',
},
computed: {
visibleItems() {
return this.items.slice(0, this.count)
}
},
created() {
// Define the data upfront so it will be reactive
for (let i = 0; i < this.maxCount; i++) {
this.items.push({
firstName: '',
lastName: '',
})
}
},
methods: {
submit() {
// Transform the data into some JSON that is
// compatible with your API
const data = this.visibleItems.map(item => ({
first_name: item.firstName,
last_name: item.lastName,
role: 'user',
}))
this.data = JSON.stringify(data, null, ' ')
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
Number of people:
<select v-model="count">
<option v-for="i of maxCount" :value="i">{{ i }}</option>
</select>
</div>
<div v-for="item of visibleItems">
<input placeholder="First name" v-model="item.firstName">
<input placeholder="Last name" v-model="item.lastName">
</div>
<button #click="submit">Submit</button>
<pre>{{ data }}</pre>
</div>
Try this example.
<div id="app">
<div>
<select v-model="jumlahlow">
<option v-for="i in selects" :key="i">{{ i }}</option>
</select>
</div>
<div v-for="num, index in parseInt(jumlahlow)">
<input v-model="lows[index].value" />
</div>
</div>
And JS
new Vue({
el: '#app',
data: {
lows: [
{
value: ''
}
],
jumlahlow: 1,
selects: [
1,
2,
3,
4,
5,
6
]
},
watch: {
jumlahlow: function (val) {
this.lowsTmp = this.lows;
this.lows = [];
for (let i = 0; i < val; i++) {
const currentVal = typeof this.lowsTmp[i] !== 'undefined' ? this.lowsTmp[i].value : '';
this.addLow(currentVal);
}
}
},
methods: {
addLow: function(val) {
this.lows.push({ value: val });
}
}
})
Directly check here: https://jsfiddle.net/abinhho/m3c8r4tj/2/
you are iterating v-for="n in parseInt(form.jumlahlow)" but that's an Object and v-for works on array not on objects.
Here you can use array of objects to iterate, for example:-
form: [{
jumlahlow: 1,
checked: [],
low: []
}]
and after that you will have to write v-for="n in form" then try accessing low by form.low

Vue-MultiSelect Checkbox binding

The data properties of the multi-select component does not update on change. Check-boxes doesn't update on the front-end.
Expected Behavior: The check-boxes should get ticked, when clicked.
Link to code: https://jsfiddle.net/bzqd19nt/3/
<div id="app">
<multiselect
select-Label=""
selected-Label=""
deselect-Label=""
v-model="value"
:options="options"
:multiple="true"
track-by="library"
:custom-label="customLabel"
:close-on-select="false"
#select=onSelect($event)
#remove=onRemove($event)
>
<span class="checkbox-label" slot="option" slot-scope="scope" #click.self="select(scope.option)">
{{ scope.option.library }}
<input class="test" type="checkbox" v-model="scope.option.checked" #focus.prevent/>
</span>
</multiselect>
<pre>{{ value }}</pre>
</div>
new Vue({
components: {
Multiselect: window.VueMultiselect.default
},
data: {
value: [],
options: [
{ language: 'JavaScript', library: 'Vue.js', checked: false },
{ language: 'JavaScript', library: 'Vue-Multiselect', checked: false },
{ language: 'JavaScript', library: 'Vuelidate', checked: false }
]
},
methods: {
customLabel(option) {
return `${option.library} - ${option.language}`;
},
onSelect(option) {
console.log('Added');
option.checked = true;
console.log(`${option.library} Clicked!! ${option.checked}`);
},
onRemove(option) {
console.log('Removed');
option.checked = false;
console.log(`${option.library} Removed!! ${option.checked}`);
}
}
}).$mount('#app');
In your code you call onSelect and try to change the option argument of this function inside the function:
option.checked = true;
This affects only the local variable option (the function argument). And doesn't affect objects in options array in the data of the Vue instance, the objects bound with checkboxes. That's why nothing happens when you click on an option in the list.
To fix it find the appropriate element in options array and change it:
let index = this.options.findIndex(item => item.library==option.library);
this.options[index].checked = true;
Here is the code snippet with fix:
new Vue({
components: {
Multiselect: window.VueMultiselect.default
},
data: {
value: [],
options: [
{ language: 'JavaScript', library: 'Vue.js', checked: false },
{ language: 'JavaScript', library: 'Vue-Multiselect', checked: false },
{ language: 'JavaScript', library: 'Vuelidate', checked: false }
]
},
methods: {
customLabel (option) {
return `${option.library} - ${option.language}`
},
onSelect (option) {
console.log("Added");
let index = this.options.findIndex(item => item.library==option.library);
this.options[index].checked = true;
console.log(option.library + " Clicked!! " + option.checked);
},
onRemove (option) {
console.log("Removed");
let index = this.options.findIndex(item => item.library==option.library);
this.options[index].checked = false;
console.log(option.library + " Removed!! " + option.checked);
}
}
}).$mount('#app')
* {
font-family: 'Lato', 'Avenir', sans-serif;
}
.checkbox-label {
display: block;
}
.test {
position: absolute;
right: 1vw;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link href="https://unpkg.com/vue-multiselect#2.0.2/dist/vue-multiselect.min.css" rel="stylesheet"/>
<script src="https://unpkg.com/vue-multiselect#2.0.3/dist/vue-multiselect.min.js"></script>
<div id="app">
<multiselect
select-Label=""
selected-Label=""
deselect-Label=""
v-model="value"
:options="options"
:multiple="true"
track-by="library"
:custom-label="customLabel"
:close-on-select="false"
#select=onSelect($event)
#remove=onRemove($event)
>
<span class="checkbox-label" slot="option" slot-scope="scope" #click.self="select(scope.option)">
{{ scope.option.library }}
<input class="test" type="checkbox" v-model="scope.option.checked" #focus.prevent/>
</span>
</multiselect>
<pre>{{ value }}</pre>
</div>

Vue Component Communication (Parent > Children)

I have a parent component (todo-list) with a child component inside (todo-item). I am trying to create a checkbox(check all todos) in the parent so that when all todos will be checked with one click.
With the checkAll() in the parent component, it change the props of the child but it does not change the data of the child.
This is the parent component todo-list
<template>
<div class="todo-list-container">
<todo-input #addTodo="addTodo"></todo-input>
<todo-item v-for="(todo, index) in todos"
:key="todo.id"
:todo="todo"
:index="index"
:completed="todo.completed"
#removeTodo="removeTodo"
#changedCompleted="changedCompleted"
></todo-item>
<div class="flex-container">
<div class="button-aux-div"></div>
<a href="#" class="todo-button">
<input type="checkbox" :checked="!anyRemaining" #change="checkAll">
</a>
</div>
</div>
</template>
<script>
import Vue from 'vue'
import TodoItem from './TodoItem'
import TodoInput from './TodoInput'
export default {
name: 'todo-list',
components: {
TodoItem,
TodoInput,
},
data () {
return {
idForTodo: 3,
todos: [
{
'id': '1',
'title': 'title1',
'body': 'body1',
'completed': false,
},
{
'id': '2',
'title': 'title2',
'body': 'body2',
'completed': false,
},
],
allChecked: false,
}
},
computed: {
remaining() {
return this.todos.filter(todo => !todo.completed).length
},
anyRemaining() {
return this.remaining != 0
}
},
methods: {
addTodo(todoMessage) {
this.todos.push({
id: this.idForTodo,
title: 'title' + this.idForTodo,
body: todoMessage,
completed: false,
})
this.idForTodo++;
},
removeTodo(data) {
this.todos.splice(data.index, 1);
this.idForTodo--;
},
changedCompleted(data) {
this.todos.splice(data.index, 1, data.todo)
},
checkAll() {
this.todos.forEach((todo) => todo.completed = event.target.checked)
},
},
}
</script>
This is the child componenet todo-item
<template>
<div class="todo-item-container">
<div class="todo-title-container">
<div class="todo-id-container">
<div id="todo-id">
<h2>{{ id }}</h2>
</div>
</div>
<div id="todo-title"><h2>{{ title }}</h2></div>
<div class="todo-completed-container">
<a href="#" class="todo-button">
<input type="checkbox" v-model="completed" #change="changedCompleted">
</a>
</div>
<div class="todo-delete-container">
×
</div>
</div>
<hr>
<div class="todo-body-container">
<p id="todo-body">{{ body }}</p>
</div>
</div>
</template>
<script>
export default {
name: 'TodoItem',
props: {
todo : {
type: Object,
required: true,
},
index : {
type: Number,
required: true,
},
},
data () {
return {
'id': this.todo.id,
'title': this.todo.title,
'body': this.todo.body,
'completed': this.todo.completed,
}
},
methods: {
deletedTodo() {
this.$emit('removeTodo', {
'index': this.index,
'todo': {
'id': this.id,
'title': this.title,
'body': this.body,
'completed': this.completed,
}
})
},
changedCompleted() {
this.$emit('changedCompleted', {
'index': this.index,
'todo': {
'id': this.id,
'title': this.title,
'body': this.body,
'completed': this.completed,
}
})
},
},
}
</script>
Instead of 'completed': this.todo.completed, .
Use
computed: {
completed () {
return this.todo.completed
}
}