I made a component to provide a select including a button that reset the select to the initial state (no option selected).
I get well the onchange event in parent when an option is selected but nothing when the reset button is clicked, although the select is reset. In my use case the list is still filtered even when nothing is selected
Here is the parent file :
<template>
<liste-filter
:nom="'marque'"
:label="'Choose a make'"
:liste="marques"
v-model="selMarque"
#change="changefilter"></liste-filter>
<h1/>
<div v-for="vh in vehicules" :key="vh.lib" class="w-full">
{{ vh.lib }}
</div>
<div v-if="vehicules.length === 0">The list is empty</div>
</template>
<script>
import ListeFilter from "./ListeFilter.vue"
export default {
components: {
ListeFilter
},
data() {
return {
marques:[{id:"Renault",libelle:"Renault"},{id:"Peugeot",libelle:"Peugeot"}],
selMarque: "",
vehicules: [],
tabData:[{"lib":"Renault","modeles":[{"lib":"Clio"},{"lib":"Captur"}]},{"lib":"Peugeot","modeles":[{"lib":"208"},{"lib":"308"},{"lib":"3008"}]}]
};
},
methods: {
changefilter() {
this.vehicules = [];
for (var i = 0; i < this.tabData.length; i++) {
if(this.selMarque != "" && this.tabData[i].lib == this.selMarque) {
this.vehicules = this.tabData[i].modeles;
}
}
}
}
}
</script>
And here is the component file ListeFilter.vue :
<template>
<span class="relative">
<select
:name="nom"
:id="nom"
:label="label"
v-model="sel"
class="w-64 text-sm"
>
<option disabled value="">{{ label }}</option>
<option v-for="elem in liste" :value="elem.id" :key="elem.id">
{{ elem.libelle }}
</option>
</select>
<button
v-show="sel"
#click="reset"
>X</button>
</span>
</template>
<script>
export default {
props: ["nom", "label", "liste", "modelValue"],
emits: ["update:modelValue"],
computed: {
sel: {
get() {
return this.modelValue;
},
set(value) {
this.$emit("update:modelValue", value);
},
},
},
methods: {
reset() {
this.sel = ""
},
},
};
</script>
I also made a Vue SFC Playground to test HERE
Thanks in advance for your help.
PS : if you know a component that does the same I take it ! (vue-select does not seem Vue 3 compliant)
I think you should be listening for the #update:modelValue="changefilter" event instead of the change event #change="changefilter".
It's documented here. https://v3-migration.vuejs.org/breaking-changes/v-model.html#overview
Try changing your App.vue to this.
Here is a Playground
<template>
<liste-filter
:nom="'marque'"
:label="'Choose a mark'"
:liste="marques"
v-model="selMarque"
#update:modelValue="changefilter"
>
</liste-filter>
<h1/>
<div v-for="vh in vehicules" :key="vh.lib" class="w-full">
{{ vh.lib }}
</div>
<div v-if="vehicules.length === 0">The list is empty</div>
</template>
<script>
import ListeFilter from "./ListeFilter.vue"
export default {
components: {
ListeFilter
},
data() {
return {
marques:[{id:"Renault",libelle:"Renault"},{id:"Peugeot",libelle:"Peugeot"}],
selMarque: "",
vehicules: [],
tabData:[{"lib":"Renault","modeles":[{"lib":"Clio"},{"lib":"Captur"}]},{"lib":"Peugeot","modeles":[{"lib":"208"},{"lib":"308"},{"lib":"3008"}]}]
};
},
methods: {
changefilter() {
console.log('change happened');
this.vehicules = [];
for (var i = 0; i < this.tabData.length; i++) {
if(this.selMarque != "" && this.tabData[i].lib == this.selMarque) {
this.vehicules = this.tabData[i].modeles;
}
}
}
}
}
</script>
Related
How are you?
I'm studying Vue and I'm stuck on the current task not knowing where to go.
I have a select that when I click I need to show on screen only what corresponds to that selection. For example, when placing the "to do" option in the select, only the tasks with a concluded=false should appear on the screen. I've only gotten this far and I need help to continue. Can you help me? Thanks
This is my App.vue
<template>
<div id="app">
<h1>Lista de Tarefas</h1>
<List :data="list" #remove="handleRemove"/>
<Form #add="addNewTask" #onChange="handleN"/>
</div>
</template>
<script>
import List from "./components/List.vue";
import Form from "./components/Form.vue";
export default {
components: {
List,
Form,
},
data() {
return {
list: [],
};
},
methods: {
addNewTask(newTask) {
this.list.push(newTask);
},
handleRemove(item) {
const index = this.list.findIndex(i => i.id === item.id)
this.list[index].excluded = true
},
handleN(item) {
const index = this.list.findIndex(i => i.id === item.id)
this.list[index].concluded = true
}
},
};
</script>
This is my List.vue
<template>
<ul>
<select v-model="selected" #change="onChange($event)">
<option disabled value="">Escolha a visualização</option>
<option v-for="option in options" :key="option.text">
{{ option.text }}
</option>
</select>
<li v-for="item in itens" :key="item.id">
<input type="checkbox" id="checkbox" v-model="item.concluded" />
<label for="checkbox"> {{ item.description }} </label>
<button #click="() => $emit('remove', item)">Excluir</button>
</li>
</ul>
</template>
<script>
export default {
props: {
data: {
type: Array,
default: () => {},
},
},
data() {
return {
selected: "",
options: [
{ text: "Todos", value: "1" },
{ text: "A fazer", value: "2" },
{ text: "Concluído", value: "3" },
{ text: "Deletado", value: "4" },
],
};
},
computed: {
itens() {
return this.data.filter((item) => item.excluded === false);
},
},
methods: {
onChange(event) {
console.log(event.target.value);
return this.data.filter((item) => item.concluded === false);
},
},
};
</script>
This is my Form.vue
<template>
<form #submit.prevent="handleNewTask">
<input type="text" v-model="newTask" placeholder="Insira a tarefa"/>
<input type="submit" value="Adicionar"/>
</form>
</template>
<script>
import Task from '../types/Task.js'
export default {
data() {
return {
newTask: "",
};
},
methods: {
handleNewTask() {
this.$emit('add', new Task(this.newTask))
this.newTask = ''
}
},
};
</script>
And this is my Task.js
export default class {
constructor(description) {
this.description = description,
this.id = Math.random(),
this.concluded = false,
this.excluded = false
}
}
I watch some tutorials, read the documentation and some StackOverflow questions but I really can't get out of here
Thanks in advance for the help
Based on how you have structured your app, our only concern should be with the List.vue file.
Your goal is to filter the results based on the selection (selected property). However, your issue is that you are not even using that anywhere.
I know you are hard coding the filter on the onChange method but that is, first of all wrong because you aren't really changing anything (you are returning an array), and secondly it's inefficient.
A better way to do it is to update the computed itens function like so:
itens() {
return this.data.filter((item) => {
if (this.selected === '1'){
return item.concluded === false
} else if (this.selected === '2'){
// filter another way
} else if (... // so on and so forth
});
},
Also, I would filter out the excluded items before sending them to the component. If you aren't going to use it, don't send it.
Remove the onChange event on the <select> and the associated method since they are now unused.
I'm create a an component which represents my money field.
My target is on add element in list, set zero on money field to add next element in list...
But, my problem is that not working when send using $emit event to clear input to improve usability.
$emit works as described on image bellow
My money field:
<template>
<div class="input-group" #clear="clearInputField()">
<span>{{ title }}</span>
<input ref="displayMoney" type="text" v-model="displayMoney" #focus="isActive = true" #blur="isActive = false" />
</div>
</template>
<script>
export default {
props: {
title: String,
},
data() {
return {
money: 0,
isActive: false,
};
},
methods: {
clearInputField() {
console.log("Its work event");
this.money = 0;
this.displayMoney = "";
},
},
computed: {
displayMoney: {
get: function () {
if (this.isActive) {
return this.money;
} else {
return this.money.toLocaleString("pt-br", { style: "currency", currency: "BRL" });
}
},
set: function (modifiedMoney) {
let newMoney = parseFloat(modifiedMoney.replace(/[^\d.]/g, "."));
if (isNaN(newMoney) || newMoney.length == 0) {
newMoney = 0;
}
this.$emit("input", newMoney);
return (this.money = parseFloat(newMoney));
},
},
},
};
</script>
My principal component
<template>
<div class="wish-list">
<div class="row">
<div class="input-group">
<span>Digite sua meta: </span>
<input ref="descriptionWish" type="text" v-model="descriptionWish" />
</div>
<MoneyField title="Valor (R$): " v-model="valueWish" #keyup.native.enter="addWish" />
<button id="btnCalculate" #click="addWish()">Adicionar a lista de desejos</button>
</div>
<div class="list-items">
<ul>
<li v-for="wish in wishes" :key="wish">{{ wish }}</li>
</ul>
</div>
</div>
</template>
<script>
import MoneyField from "./Fields/MoneyField";
export default {
components: {
MoneyField,
},
data() {
return {
wishes: [],
valueWish: 0,
descriptionWish: "",
};
},
methods: {
addWish() {
if (!isNaN(this.valueWish) && this.valueWish > 0 && this.descriptionWish.length > 0) {
this.wishes.push(
`${this.descriptionWish} => ${this.valueWish.toLocaleString("pt-BR", { currency: "BRl", style: "currency" })}`
);
this.descriptionWish = "";
console.log("addWish");
this.valueWish = 0;
this.$emit("clear");
this.$refs.descriptionWish.focus();
}
this.valueWish = 0;
},
},
};
</script>
I still don't understand much about vueJS, but I believe it's something related to parent and child elements, but I've done numerous and I can't get my answer.
sorry for my bad english .
The emit sends an event from the child to the parent component not as you've done, to run a method from the child component you could add a ref in the component inside the parent one like :
<MoneyField title="Valor (R$): "
ref="moneyField" v-model="valueWish" #keyup.native.enter="addWish" />
then run this.$refs.moneyField.clearInputField() instead this.$emit("clear")
I have a parent component as a Cart. Here I defined quantity and I want to pass this quantity to the child component's input value which is Counter. So here how I am passing it and here is my parent component, Cart:
<Counter quantity="item.quantity"/>
And here is my child component, Counter:
<template>
<div id="counter">
<button class="minus" #click="countDown"><i :class="quantity == 0 ? 'disabled' : ''" class="fas fa-minus"></i></button>
<div class="count-number"><input class="counter-content" type="number" v-model="quantity"></div>
<button class="plus" #click="countUp"><i class="fas fa-plus"></i></button>
</div>
</template>
<script>
export default {
props: {
quantity: Number
},
methods: {
countUp() {
this.quantity++;
},
countDown() {
if(this.quantity > 0) {
this.quantity--;
}
},
}
}
</script>
I am quite new in Vue, so maybe I am doing something wrong when I pass the props. So could you help me about this?
Try (with the : colon sign)
<Counter :quantity="item.quantity"/>
Before you were just passing the string "item.quanity"
I see you're modifying your prop directly:
countUp() {
this.quantity++;
},
countDown() {
if(this.quantity > 0) {
this.quantity--;
}
},
This is not how you do it in Vue. You need to use two way binding.
countUp() {
this.$emit('input', this.quantity+1)
}
countDown() {
this.$emit('input', this.quantity-1)
}
and in your parent component:
<Counter :quantity="item.quantity" #input="(payload) => {item.quantity = payload}"/>
By the way, the Vue styleguide recommends to use multi-word component names: https://v2.vuejs.org/v2/style-guide/#Multi-word-component-names-essential (Cart = bad, MyCart = good)
We cannot change the value that we get from props, so I created a variable and put props there when mounting
Try it
<Counter :quantity="item.quantity"/>
and
<template>
<div id="counter">
<button class="minus" #click="countDown"><i :class="sum == 0 ? 'disabled' : ''" class="fas fa-minus"></i></button>
<div class="count-number"><input class="counter-content" type="number" v-model="sum"></div>
<button class="plus" #click="countUp"><i class="fas fa-plus"></i></button>
</div>
</template>
<script>
export default {
props: {
quantity: Number
},
data: () => ({
sum: 0
}),
mounted() {
this.sum = this.quantity;
},
methods: {
countUp() {
this.sum++;
},
countDown() {
if(this.sum > 0) {
this.sum--;
}
},
}
}
</script>
Good afternoon, tell me please, I wrote a calendar displaying the events that the user sets, and now I want to make a detailed display of the event when I click it. The problem is that the events are in my component and the whole display logic is in another, how can I use them together.I want to make it so that the getDetailInformation() function in the ModalWindowDetail component component is called by clicking on an event in another component Calendar.vue. I use the event bus, but nothing works for me, I don’t understand why. Please help me solve this problem.
Screenshot of Calendar and error in console
Code of Calendar on GitHub
App.vue:
<template>
<div class="all">
<app-calendar #sendTextEvent="text = $event"></app-calendar>
<app-detail v-if="modalWindowDetail"
:eventText="text"></app-detail>
</div>
</template>
<script>
import appCalendar from './components/Calendar.vue'
import appDetail from './components/ModalWindowDetail.vue'
export default {
data(){
return{
text: String
}
},
components: {
appCalendar,
appDetail
},
computed: {
modalWindowDetail() {
return this.$store.state.modalWindowDetail;
}
}
};
</script>
Calendar.vue component which display calendar:
<template>
<div class="overflow-div">
<transition :name="nameOfClass" >
<div :key="currentPage" class="fade_wrapper">
<div v-for="(week, i) in getCalendar" class="d_day">
<li v-for="day in week" class="li_day">
<div class="day">{{ day }}</div>
<div v-for="event in buildEvents(i, day)"
class="event"
v-bind:class="{ 'eventBrown': eventBrown(event),
'eventPurple': eventPurple(event),
'eventOrange': eventOrange(event),
'eventBlue': eventBlue(event) }"
v-on:click="openModalDetail(event)">{{ event }}
</div>
</li>
</div>
</div>
</transition>
</div>
</template>
<script>
import json from './Calendar_data.json'
import { mapState } from "vuex";
import { eventBus } from './../main.js'
export default {
mounted(){
eventBus.$on('getDetailInformation', this.openModalDetail())
},
computed: {
modalWindowDetail() {
return this.$store.state.modalWindowDetail;
},
},
methods: {
openModalDetail(text){
this.$emit('sendTextEvent', text);
}
};
</script>
The component in which the getDetailInformation() is located ModalWindowDetail.vue:
<template>
<div class="underModalWindow">
<div class="modalWindow">
<img src="src/assets/x.png" width="20px" height="20px">
<div class="nameofModal">Вся детальная информация о событии</div>
<div v-for="(key, name) in eventDetail" class="detailEvent">{{ name }}: {{ key }}</div>
<button>Окей</button>
</div>
</div>
</template>
<script>
import { eventBus } from './../main.js'
export default {
props: ['eventText'],
data(){
return{
options: [
{ text: 'Встреча', value: '8' },
{ text: 'День Рождения', value: '4' },
{ text: 'Праздник', value: '1' },
{ text: 'Другое', value: '16' }
],
eventDetail: Object,
}
},
computed: {
eventsData() {
return this.$store.state.eventData;
},
modalWindowDetail() {
return this.$store.state.modalWindowDetail;
},
},
created(){
eventBus.$emit('getDetailInformation', this.getDetailInformation())
},
methods: {
getDetailInformation(){
let arrOfEvents = this.eventsData.events;
for(let z = 0; z < arrOfEvents.length; z++){
let memo = arrOfEvents[z].memo;
console.log(this.memo)
if(memo === this.eventText){
let dataStartOfEvent = arrOfEvents[z].starts_at;
let getStartDataOfEvent = new Date(dataStartOfEvent);
let dataEndOfEvent = arrOfEvents[z].ends_at;
let getEndDataOfEvent = new Date(dataEndOfEvent);
if((getStartDataOfEvent.getHours() - 3) > 0){
this.$store.commit('changeModalWindowDetail', this.modalWindowDetail);
this.eventDetail = {
'Событие': this.eventText,
'Начало события': getStartDataOfEvent.toLocaleTimeString(),
'Конец события': getEndDataOfEvent.toLocaleTimeString(),
'Тип события': this.getType(arrOfEvents[z].type)
}
}else if(getStartDataOfEvent.getDate() != getEndDataOfEvent.getDate()){
this.$store.commit('changeModalWindowDetail', this.modalWindowDetail);
this.eventDetail = {
'Событие': this.eventText,
'Начало события': getStartDataOfEvent.toLocaleDateString(),
'Конец события': getEndDataOfEvent.toLocaleDateString(),
'Тип События': this.getType(arrOfEvents[z].type)
}
}
}
}
}
}
};
</script>
You should remove the () from the function name in eventBus.$on('getDetailInformation', this.openModalDetail()) - you want to reference the function, not to call it and use the result as a reference.
Also, your function getDetailInformation() does not return anything - but you seem to expect that it returns a text. You should correct this.
And finally, I think that #sendTextEvent="text = arguments[0]" would be more appropriate - and using a dedicated method/function will be the best.
App (parent)
Hi I have these component (Child)
TextComponent
InfoErrorForm
When I press submit from the parent component App is not validate this form. So I tried to validate with inject $validator in the child component (TextComponent), and provide but not show message error .
If you can help me to validate children form inisde parent component.
This is my code
AppComponent
<template>
<div>
<!-- Form validar numero max input -->
<form :class="{'was-validated': error_in_form_save_progress}" >
<card-shadow v-for="(texto,key) in sections_template.texts" :key="key" >
<texto-component
:orden="key+2"
v-model="sections_template.texts[key].content"
:tituloComponente="texto.title"
:inputName="texto.title" >
<template slot="section_show_error_validate_input">
<info-error-form
:listErrors='errors'
:name_field = "texto.title"
v-show = "error_in_form_save_progress" >
</info-error-form>
</template>
</texto-component>
</card-shadow>
</form>
<div class="row foot_button" >
<div class="offset-md-3 col-md-3">
<button class="btn" #click.prevent="save_progrees"> Guardar Cambios</button>
</div>
</div>
</div>
</template>
<script>
export default {
provide() {
return {
$validator: this.$validator,
};
},
data: function(){
return {
sections_template: {
texts:[
{
section_template_id: 1,
type: "texto",
title: "fundamentacion",
content: ""
},
{
section_template_id: 2,
type: "texto",
title: "sumilla",
content: ""
}
] },
error_in_form_save_progress: true
}
},
methods:{
save_progrees(){
this.$validator.validateAll().then((result) => {
if (result) {
this.error_in_form_save_progress = false;
alert("se guardaran cambios");
return
}
this.error_in_form_save_progress = true;
});
}
}
}
</script>
I found solution with this code. In my parent component i add provide and i send the $validator
export default {
components:{
...
},
provide() {
return {
$validator: this.$validator,
}
},
In my child component i received this
inject: ['$validator'],
In my parent component i add this method to invoque validation
methods:{
save_progrees(){
var validationArray = this.$children.map(function(child){
return child.$validator.validateAll();
});
window.Promise.all(validationArray).then((v) => {
v.some( element => { if ( element == false ) { throw "exists error in child component";} });
this.error_in_form_save_progress = false;
alert("datos guardados");
return
}).catch(() => {
this.show_message_error_validation();
});
},
show_message_error_validation(){
this.error_in_form_save_progress = true;
}
}
Finally to show error in component info-error I use this code
<template>
<div class="row" v-if="errors.items">
<div class="col-md-12">
<template v-for="(e,key) in errors.items" >
<div class="text-danger" v-if="e.field ==name_field" :key="key"> {{e.msg}} </div>
</template>
</div>
</div>
</template>
In your child component do watch for this.errors and in the watch, put this.$emit
Something like this below :
watch: {
errors: function (value) {
this.$emit('TextComponent', value)
}
}
And then catch it on your parent component see it here https://v2.vuejs.org/v2/api/#vm-emit