how to detect clear button click on v-select (vue-select) - javascript

I was creating a drop-down in v-select, after selecting a option when clicking on clear button I need to clear the drop down and change option array to initial stage.
How to check clear button (x) is clicked or not, I tried with on-change is used to get selected value it is working properly and #click etc. none of them working, please help me.
<template>
<v-select
v-model="selected"
:reduce="(option) => option.id"
:options="[
{ label: 'One', id: 1 },
{ label: 'Two', id: 2 },
]"
#onChange="searchProduct"
/>
</template>
<script>
export default {
data() {
return {
selected: 3,
}
},
methods(){
searchProduct(selected){
console.log('selected value ',selected)
}
}
</script>
I'm expecting something methods to handle drop-down clear event.

As we don't have any explicit event yet, we can achieve this requirement by watching the v-model value.
watch: {
selected(value) {
if (!value) {
// Your logic here
}
}
}
Live Demo as per the requirement :
Vue.component("v-select", VueSelect.VueSelect);
new Vue({
el: "#app",
data: {
selected: 3
},
watch: {
selected(value) {
if (!value) {
this.selected = 3;
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-select/3.10.3/vue-select.js"></script>
<link rel="stylesheet" href="https://unpkg.com/vue-select/dist/vue-select.css"/>
<div id="app">
<v-select
v-model="selected"
:reduce="(option) => option.id"
:options="[
{ label: 'One', id: 1 },
{ label: 'Two', id: 2 },
]"
/>
</div>

Related

Vue 3 custom checkbox component with v-model and array of items

Desperately in need of your help guys.
So basically I have a custom checkbox component whit a v-model. I use a v-for loop on the component to display checkboxes with the names from the array. In the parent component I have two columns Available and Selected. The idea is that if I check one of the boxes in the Available column it should appear on the Selected column. The problem is that it displays letter by letter and not the full name.
I am able to achieve the desired result without having a checkbox component, but since I will be needing checkboxes a lot throught my project I want to have a component for it.
Please follow the link for the code:
CodeSandBox
Dont mind the difference in styling.
The problem:
The desired outcome:
There are two problems. The first problem is, that you have your v-model set to v-model="filter.filterCollection", so a checkbox you select will be stored into the array as a string and if you select another checkbox the string gets overwritten. The second problem is, that you call that stored string as an array. That causes, that your string, which is an array of letters, will be rendered for each letter. So 'Number' is like ["N", "u", "m", "b", "e", "r"].
To solve your problem, you need to store every selection with its own reference in your v-model. To cover your needs of correct listing and correct deleting you need to apply the following changes:
Your checkbox loop
<Checkbox
v-for="(item, index) in items"
:key="item.id"
:label="item.name"
:id="index"
:isChecked="isChecked(index)" // this is new
#remove-selected-filter="removeSelectedFilter" // This is new
:modelValue="item.name"
v-model="filter.filterCollection[index]" // Change this
/>
Your v-model
filter: {
filterCollection: {} // Object instead of array
}
Methods in FilterPopUp.vue
methods: {
removeSelectedFilter(index) {
delete this.filter.filterCollection[index];
},
isChecked(index) {
return !!this.filter.filterCollection[index];
}
}
Your Checkbox.vue:
<template>
<label>
<p>{{ label }}</p>
<input
type="checkbox"
:id="id"
:value="modelValue"
:checked="isChecked"
#change="emitUncheck($event.target.checked)"
#input="$emit('update:modelValue', $event.target.value)"
/>
<span class="checkmark"></span>
</label>
</template>
<script>
export default {
name: "Checkbox",
props: {
modelValue: { type: String, default: "" },
isChecked: Boolean,
label: { type: String },
value: { type: Array },
id: { type: Number },
},
methods: {
emitUncheck(event) {
if(!event){
this.$emit('remove-selected-filter', this.id);
}
}
}
};
</script>
This should now display your items properly, delete the items properly and unselect the checkboxes after deleting the items.
StevenSiebert has correctly pointed to your errors.
But his solution is not complete, since the filters will not be removed from the collection when you uncheck one of them.
Here is my complete solution of your checkbox working as expected:
Checkbox.vue
<template>
<label>
<p>{{ label }}</p>
<input
type="checkbox"
:id="id"
v-model="checked"
#change="$emit('change', { id: this.id, checked: this.checked})"
/>
<span class="checkmark"></span>
</label>
</template>
<script>
export default {
name: "Checkbox",
props: {
modelValue: { type: Boolean, default: false },
label: { type: String },
id: { type: Number },
},
emits: ["change"],
data() {
return {
checked: this.modelValue
};
}
};
</script>
FilterPopUp.vue
<template>
...
<Checkbox
v-for="(item, index) in items"
:key="index"
:label="item.name"
:id="index"
#change="onChange"
/>
...
</template>
<script>
...
methods: {
removeSelectedFilter(index) {
this.filter.filterCollection.splice(index, 1);
},
onChange(args) {
const {id, checked} = args;
const item = this.items[id].name;
if (checked) {
if (this.filter.filterCollection.indexOf(item) < 0) {
this.filter.filterCollection.push(item);
}
} else {
this.filter.filterCollection = this.filter.filterCollection.filter( i=> i != item);
}
},
},
...
Here is the working CodeSandbox:
https://codesandbox.io/s/pensive-shadow-ygvzb?file=/src/components/Checkbox.vue
Sure, there are many ways to do it. If somebody has a nicer and shorter way to do it, please post your solution. It will be interesting to look at it.

Reset filtered data Vue.js

I need to implement a button that would drop the filters in my application. The application is written on Vue. The filters themselves were implemented, but I do not know how to implement their reset.
<template>
<div id="app">
<input type="text" v-model="search">
<select name="sort" v-model="sort">
<option v-for="option in options" :value="option.value" :label="option.label"></option>
</select>
<table>...</table>
</div>
</template>
<script>
import goodsList from './api/data';
export default {
name: 'app',
data() {
return {
search: '',
sort: '',
options: [
{ label: 'Default', value: 'none' },
{ label: 'Brand', value: 'brand' },
{label: 'Price', value: 'price'}
],
goods: goodsList,
}
},
computed: {
filteredList() {
let filteredGoods = this.goods.filter( item => {
return item.name.toLowerCase().includes(this.search.toLowerCase());
});
switch (this.sort) {
case 'brand':
filteredGoods.sort((a, b) => a.brand.localeCompare(b.brand));
break;
case 'price':
filteredGoods.sort((a, b) => parseInt(a.price - b.price));
break;
}
return filteredGoods;
}
},
}
</script>
You will need a reset function which will assign the default selected value eg: 'none' to the v-model 'sort'. Since it is a two way binding, changing the value of 'sort' variable will eventually reset the selected option.
Function to be added:
resetOptions: function () {
this.sort='none';
}
Link below
https://jsfiddle.net/RohanPatil/68wced20/9/

How to enable second dropdown list only after the first dropdown is selected?

I've dynamically created three dropdown lists using v-for. Now, I have trouble performing the following task. For example,
1) I want the first dropdown list to be enabled so that users can select an option.
2) The second and third dropdowns cannot be selected yet and must be disabled.
3) After the user selected an option from the first dropdown, the second dropdown will be enabled but the third dropdown will remain disabled
4) After the user selected an option from the second dropdown, the third dropdown will be enabled for the user to select an option from it
Edit1 Still trying to solve this issue, help is greatly appreciated!
Edit2 Still trying to solve this, is there anyone that can help me?
Edit3 Here is a Codepen to work with https://codepen.io/Issaki/pen/RzzxvL
Below is my current code:
<template>
<div>
<!-- Dynamically create the select dropdowns using v-for -->
<div v-for="(attribute, index) in attributes" :key="index">
<label>{{attribute.type}}</label>
<!-- Dynamically render the id to keep track of which dropdown was selected -->
<select
#change="selectedValue($event)"
:id="'option' + index"
v-model="selectedValues[index]"
>
<option value>Select option</option>
<option v-for="(value, index) in attribute.values" :key="index">{{value}}</option>
</select>
</div>
</div>
</template>
<script>
export default {
data() {
return {
// Do note that, the size of this array is not fixed.
// At the moment, there is only three objects in the array
attributes: [
{
type: "Color",
values: ["Black", "White", "Yellow"]
},
{
type: "Size",
values: ["Small", "Medium", "Large"]
},
{
type: "Finish",
values: ["Shiny", "Glossy"]
}
],
selectedValues: []
};
},
methods: {
selectedValue(e) {
console.log(e);
console.log(this.selectedValues);
if (e.target.id === "option0") {
if (this.selectedValues[0] === "") {
document.getElementById("option1").disabled = true;
document.getElementById("option2").disabled = true;
} else {
document.getElementById("option1").disabled = true;
document.getElementById("option2").disabled = true;
}
}
}
}
};
</script>
I don't think there's any need to resort to element ids or direct manipulation of the DOM. You can keep it all in the template just by setting the disabled attribute depending on how many values have been selected.
Figuring out which select has been changed can be done just by passing the index to the #change handler.
new Vue({
el: "#app",
data: {
attributes: [
{
type: "Color",
values: ["Black", "White", "Yellow"]
},
{
type: "Size",
values: ["Small", "Medium", "Large"]
},
{
type: "Finish",
values: ["Shiny", "Glossy"]
}
],
selectedValues: []
},
methods: {
selectValue (index, value) {
const newValues = this.selectedValues.slice(0, index)
if (value) {
newValues.push(value)
}
this.selectedValues = newValues
}
}
})
<script src="https://unpkg.com/vue#2.6.10/dist/vue.js"></script>
<div id="app">
<div v-for="(attribute, index) in attributes" :key="index">
<label>{{ attribute.type }}</label>
<select
#change="selectValue(index, $event.target.value)"
:value="selectedValues[index]"
:disabled="selectedValues.length < index"
>
<option :value="undefined">Select option</option>
<option v-for="(value, index) in attribute.values" :key="index">{{ value }}</option>
</select>
</div>
<div>{{ selectedValues }}</div>
</div>

Vue js v-if condicional rendering on a shared toggle button

//PARENT COMPONENT
<template>
....
<div class="input-wrapper">//Toggle button container
<label class="input-label">
SELECT YES OR NOT
</label>
<toggle //child component, toggle button
:options="shipping"
/>
</div>
<div
v-if="destiny[0].value"
class="input-wrapper">
<label class="input-label">
IF YES THIS CONTAINER WILL BE DISPLAYED
</label>
<toggle
:options="Options"
/>
</div>
.....
</template>
<script>
import Toggle from "....";
export default {
components: {
Toggle,
},
data: function () {
return {
destiny: [{
label: 'Yes',
value: true
},
{
label: 'No',
value: false
}
],
Options: [{
label: 'A',
value: 'a'
},
{
label: 'B',
value: 'b'
},
{
label: 'C',
value: 'c'
}]
}
}
}
</script>
///CHILD COMPONENT
<template>
<div class="toggle">
<button
v-for="option in options"
:key="option.value"
:class="{
active: option.value === value
}"
class="btn"
#click="() => toggleHandler(option.value)">{{ option.label }} .
</button>
</div>
</template>
<script>
export default {
props: {
options: {
type: Array,
required: true
}
},
data: function () {
return {
value: this.options[0].value
}
},
methods: {
toggleHandler (value) {
this.$emit('input', value)
this.value = value
}
}
}
</script>
There is toggle with to options YES or NOT, if yes is selected the child component will be rendered otherwise will keep hide.
I'm trying to use a conditional in order to display a child component into a parent component using directives v-if or v-show, but I could not find the way to send the boolean value from the child component to the parent component.
Hope this helps!!
// CHILD
Vue.component('child', {
template: '<div>TOGGLE:- <input type="checkbox" #click="emit"/></div>',
data() {
return {
checked: false
};
},
methods: {
emit: function() {
this.checked = !this.checked;
this.$emit('event_child', this.checked);
}
}
});
// PARENT
var vm = new Vue({
el: '#app',
data: function() {
return {
toggleStatus: false
}
},
methods: {
eventChild: function(checked) {
this.toggleStatus = checked;
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<div id="app">
<child v-on:event_child="eventChild"></child>
<div id="toggle">TOGGLE STATUS => {{toggleStatus}}</div>
</div>

proper use of Vue $refs

Im attempting to recreate this exact inline editing functionality in on of my vue components. However, and I may be wrong, I see some of the syntax is outdated Vue, in particular the v-el directive being used. I've attempted to update the syntax like so:
new Vue({
el: '#app',
data: {
numbers: [{
val: 'one',
edit: false
},
{
val: 'two',
edit: false
},
{
val: 'three',
edit: false
}
]
},
methods: {
toggleEdit: function(ev, number) {
number.edit = !number.edit
// Focus input field
if (number.edit) {
Vue.nextTick(function() {
ev.$refs.input.focus(); // error occurs here
})
}
},
saveEdit: function(ev, number) {
//save your changes
this.toggleEdit(ev, number);
}
}
})
<div id="app">
<template v-for="number in numbers">
<span v-show="!number.edit"
v-on:click="toggleEdit(this, number)">{{number.val}}</span>
<input type="text"
ref="input"
v-model="number.val"
v-show="number.edit"
v-on:blur="saveEdit(ev, number)"> <br>
</template>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.13/dist/vue.js"></script>
However I get a range of errors... any suggestions on how to properly execute this?
Here is the Error:
[Vue warn]: Error in nextTick: "TypeError: undefined is not an object
(evaluating 'ev.$refs.input')"
Many things changed from Vue.js 1.x to 2.x. I will walk you through the changes necessary in that snippet of yours:
v-repeat should be v-for
Replace v-el="input" with ref="input"
Since you are using ref="input" inside a v-for, then this.$refs.input will be an array of elements, not a single element.
To access each single element, you will need an index (for the array), that's why you should include the index variable in the v-for: v-for="(number, index) in numbers"
Pass the index instead of the ev to the functions, so you can get the<input>s later using vm.$refs.input[index].focus();
And that's pretty much it. After changes you'll get:
new Vue({
el: '#app',
data: {
numbers: [
{
val: 'one',
edit: false
},
{ val: 'two',
edit: false
},
{
val: 'three',
edit: false
}
]
},
methods: {
toggleEdit: function(index, number){
number.edit = !number.edit;
// Focus input field
var vm = this;
if (number.edit){
Vue.nextTick(function() {
vm.$refs.input[index].focus();
})
}
},
saveEdit: function(index, number){
//save your changes
this.toggleEdit(index, number);
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.13/dist/vue.js"></script>
<div id="app">
<template v-for="(number, index) in numbers">
<span v-show="!number.edit"
v-on:click="toggleEdit(index, number)">{{number.val}}</span>
<input type="text"
ref="input"
v-model="number.val"
v-show="number.edit"
v-on:blur="saveEdit(index, number)"> <br>
</template>
</div>
If you want the functionality and not the code design, I'd recommend you redesign it. I think you want to edit data, and the data shouldn't have to know whether it's being edited. That is the role of a component.
So let's make a component that lets you v-model data. The component itself has a span and an input. If you're editing, it shows the input, otherwise, the span. Click starts editing, blur stops editing. When editing starts, set focus on the input.
It takes a value prop. Its input element emits an input event to signal changes (per component v-model spec.
new Vue({
el: '#app',
data: {
stuff: ['one', 'two', 'three']
},
components: {
inlineEditor: {
template: '#inline-editor-template',
props: ['value'],
data() {
return {
editing: false
}
},
methods: {
startEditing() {
this.editing = true;
this.$nextTick(() => this.$refs.input.focus());
},
stopEditing() {
this.editing = false;
}
}
}
}
});
<script src="//unpkg.com/vue#latest/dist/vue.js"></script>
<div id="app">
<inline-editor v-for="item, index in stuff" v-model="stuff[index]"></inline-editor>
</div>
<template id="inline-editor-template">
<div>
<span #click="startEditing" v-show="!editing">{{value}}</span>
<input ref="input" :value="value" #input="e => $emit('input', e.target.value)" #blur="stopEditing" v-show="editing">
</div>
</template>

Categories

Resources