parent component: Groups
child component: Modal
in Groups, I have Modal as a component.
<modal
v-if="$store.getters.getClusters"
id="editIndFeedbackModal"
title="Edit group feedback"
:atok="atok"
:feedback="$store.getters.getCurrentClusterFeedback"
:hint="$store.getters.getCurrentClusterHint"
:grade="$store.getters.getCurrentClusterGrade"
:nextAss="$store.getters.getCurrentClusterNextAss"
:recRead="$store.getters.getCurrentClusterRecRead"
:link="$store.getters.getCurrentClusterLink"
:clusterName="$store.getters.getCurrentClusterName"
:clusterId="$store.getters.getCurrentClusterId"
aria-labelledby="textEditClusterName"
/>
In Modal, I have a bootstrap modal.
props: [
'id',
'ariaLabelledby',
'atok',
'file_id_arr',
'feedback',
'hint',
'grade',
'nextAss',
'recRead',
'link',
'name',
'clusterId',
'clusterName',
],
and used in Modal template as follows:
<div class="form-group">
<textarea v-model="feedback" name="text_feedback" id="text_feedback"
class="form-control" style="resize: vertical;" rows="3" placeholder="">
</textarea>
<label for="text_feedback">Feedback</label>
</div>
Since Modal saves this input form, I am using v-model to change the prop and thus getting the mutating props warning.
What I've tried:
I tried assigning the props to local data on Modal comp.:
data: function () {
return {
currentFeedback: {
atok: this.$props.atok,
feedback: this.$props.feedback,
},
}
},
atok comes back great since it exists throughout the lifecycle, yet feedback is empty since feedback comes from an async operation, where this whole issue is stemming from.
the async operation is dispatched to vuex via Groups mounted():
getAssFiles: function () {
if (this.atok) {
this.$store.dispatch('GET_ASSIGNMENT_FILES', {
assign_token: this.atok
});
}
Thank you kindly.
p.s.
this firm use allot of abbreviations, so ass = assignment..
EDIT
I've done this:
data: function () {
return {
currentFeedback: {
feedback: this.migrateFeedback,
},
}
},
computed:{
migrateFeedback(){
this.currentFeedback.feedback = this.$props.feedback
}
same result, yet when using the vue console, when I click to open the data tab, it suddenly updates view and now it's there, any idea how to solve this erroneous issue?
Related
I have a small Nuxt issue that I can't work out how to get around.
Essentially, I have an object (used for a carousel slider).
<template>
<div
:class="[$style.swiperSlide, 'swiper-slide']"
v-for="slide in slides"
:key="slide.id">
<nuxt-img
:class="[$style.img]"
:alt="slide.alt"
:src="imgSources(slide)"
sizes="sm:100vw"
/>
<div :class="[$style.info, 'info-b']" v-if="slide.info">
{{ slide.info }}
</div>
</div>
<button :class="[$style.infoOpen]"
#click="showTab"
v-if="slideInfoAvailable"
>
Close
</button>
</template>
<script>
export default {
props: {
slides: {
type: Array,
required: true,
default: () => []
}
},
computed: {
slideInfoAvailable() {
return this.slide?.info
}
},
mounted() {
const swiper = new Swiper(".swiper-container", {
. . .
});
},
methods: {
imgSources(slide) {
return `/img${slide.imgPath}.jpg`;
},
};
</script>
All works o.k, the problem is that I have a button outside of this v-for that I need to only be visible if there's slide.info but because this div is outside of the v-for it can't tell if it's available.
Cannot read property 'info' of undefined
The easiest way out of this is to add the button inside of the slider - but I can't for Z-index CSS issues. It has to be outside of the 'slider' div.
Any ideas how I can only show the button if there's slide.info? For some of my slides, there won't be.
<slider
:slides="[
{
imgPath: '/demo',
info: 'Demo info for this slide',
alt: 'Homepage'
},
{
imgPath: '/demo2',
alt: 'Homepage'
},
]"
/>
One way I could do it would be to see if .slide-active .style.info exists. If it doesn't exist then I can hide the button as slide-active is added to the active div by the slider API.
The issue is coming from the fact that you probably have some async fetching and that slides are not available upon initial render. To prevent this, you can use a computed with some optional chaining like this
export default {
computed: {
slideInfoAvailable() {
return this.slide?.info
}
}
}
Then, call it like this
<button :class="[$style.infoOpen]" #click="showTab" v-if="slideInfoAvailable">
You cannot use ?. directly in the template.
You could also do the classic way of
<button :class="[$style.infoOpen]" #click="showTab" v-if="slide && slide.info">
but it does not look as sexy IMO (but you do not need any computed).
And yeah, for this kind of thing, better to handle it with Vue than relying on some hacky dirty CSS tricks!
I'm fairly new to Vue and I've researched as much as I could, but cannot find a solution to this strange issue. I'm building a filter function for an online shop, and one section allows filtering based on values with a checkbox.
My vue template is as following:
<template>
<div>
<h3>{{data.filterLabel}}</h3>
<ul>
<li v-for="(item, index) in data.options" :key="index">
<input v-model="values" type="checkbox" :id="item" :value="item" :index="index" />
<label class="products__label products__capitalize" :for="item">{{ item }}</label>
</li>
</ul>
</div>
</template>
I am getting the options from a database, and loop through the data.options array with v-for. I have created a new empty array in
data() {
return {
values: []
};
},
as in the form-bindings example on the vue.js website here: https://v2.vuejs.org/v2/guide/forms.html#Checkbox
My script is as following:
<script>
export default {
name: "CheckBoxFilter",
data() {
return {
values: []
};
},
props: {
data: Object,
filterCheckBox: Function
},
watch: {
values: function(value) {
const optionRange = JSON.parse(JSON.stringify(this.values));
this.$emit("filterCheckBox", this.data.filterValue, optionRange);
}
}
};
</script>
For some strange reason, the $emit function works perfectly fine, and the array of products is filtered correctly in the UI. But when I check a value in the checkbox, the checkbox is not ticked. How is it possible that the checkbox is not ticked, while at the same time it is clearly correctly filtering the values?
I even looked at the :checked value with $event.target.checked which also correctly returns true or false, but the checkbox is still not ticked in the UI.
I have the same issue with radio buttons.
There are no issues with the <input type="text"> and also no issues with a <select>.
Has anyone experienced this before and if so what is the solution?
Thanks!
I tested and the UI displays the checked/unchecked checkboxes properly. Which version of Vue do you use? I'm not sure of what you want to do, but I think it would be cleaner to expose your values through a computed property:
export default {
name: "CheckBoxFilter",
props: {
data: Object,
},
data() {
return {
internalValues: [],
};
},
computed: {
values: {
get() {
return this.internalValues;
},
set(newVal) {
this.internalValues = newVal;
this.$emit("filterCheckBox", this.data.filterValue, [...newVal]);
},
},
},
};
</script>
With your current implementation, the values change are not observable and the filterCheckBox event is never emitted.
EDIT: I also don't understand why you set a filterCheckBox prop, it is not React ;)
I have a Modal component in Vue.
This Modal component has a few form fields in it:
<template>
<div :class="visible">
<input type="text" v-model="form.name">
<input type="text" v-model="form.email">
<input type="text" v-model="form.pass">
<button #click="sendForm">Submit</button>
<button #click="closeModal">Close</button>
</div>
</template>
<script>
export default {
data() {
return {
visible: false,
form: {
name: '',
email: '',
pass: ''
}
}
},
methods: {
sendForm() {
// Send form
},
showModal() {
this.visible = true
},
closeModal() {
this.visible = false
}
},
}
</script>
When the modal becomes visible, I am showing the form fields to the user. Let's say the user fills out the form fields but does not click on Submit. Instead, he closes the modal.
In the case, I want to reset the modal completely to its original form. Basically destroy the component. Then re-initialize it when the user clicks on the button to make it visible.
When the modal becomes visible again, the component should be a new instance and all the component data should be clear.
What I tried: I tried to clear the form values in the component on close. However, with more complicated forms/components it could become hard to reset each and every data property to their original state.
How can I destroy the component and re-create it? Are there any best practices for this situation?
You can create method to reset component data:
reset() {
Object.assign(this.$data, this.$options.data())
}
And call it, when you close modal.
Be carefull! It's works only on data properties.
Scenario / context
I have an overview component which contains a table and an add button. The add button opens a modal component. When i fill in some text fields in the modal and click the save button, a callback (given as prop) is called so the parent component (the overview) is updated. The save button also triggers the model toggle function so the model closes.
So far works everything like expected but when i want to add a second entry, the modal is "pre-filled" with the data of the recently added item.
Its clear to me that this happens because the model component keeps mounted in the background (so its just hidden). I could solve this by "reset" the modals data when the toggle function is triggered but i think there should be a better way.
I have a similar issue when i want to fetch data in a modal. Currently i call the fetch function in the mounted hook of the modal. So in this case the fetch happens when the parent component mounts the modal. This does not make sense as it should only (and each time) fetch when the modal is opened.
I think the nicest way to solve this is to mount the modal component dynamically when i click the "add" (open modal) button but i can't find how i can achieve this. This also avoids that a lot of components are mounted in the background which are possibly not used.
Screenshot
Example code
Overview:
<template>
<div>
// mount of my modal component
<example-modal
:toggleConstant = modalToggleUuid
:submitHandler = submitHandler />
// The overview component HTML is here
</div>
</template>
<script>
export default {
data() {
return {
modalToggleUuid: someUuid,
someList: [],
}
},
mounted() {
},
methods: {
showModal: function() {
EventBus.$emit(this.modalToggleUuid);
},
submitHandler: function(item) {
this.someList.push(item);
}
}
}
</script>
Modal:
<template>
<div>
<input v-model="item.type">
<input v-model="item.name">
<input v-model="item.location">
</div>
</template>
<script>
export default {
data() {
return {
modalToggleUuid: someUuid,
item: {},
}
},
mounted() {
// in some cases i fetch something here. The data should be fetched each time the modal is opened
},
methods: {
showModal: function() {
EventBus.$emit(this.modalToggleUuid);
},
submitHandler: function(item) {
this.someList.push(item);
}
}
}
</script>
Question
What is the best practive to deal with the above described scenario?
Should i mount the modal component dynamically?
Do i mount the component correctly and should i reset the content all the time?
You are on the right way and in order to achieve what you want, you can approach this issue with v-if solution like this - then mounted() hook will run every time when you toggle modal and it also will not be present in DOM when you are not using it.
<template>
<div>
// mount of my modal component
<example-modal
v-if="isShowModal"
:toggleConstant="modalToggleUuid"
:submitHandler="submitHandler"
/>
// The overview component HTML is here
</div>
</template>
<script>
export default {
data() {
return {
isShowModal: false,
modalToggleUuid: someUuid,
someList: []
};
},
mounted() {},
methods: {
showModal: function() {
this.isShowModal = true;
},
submitHandler: function(item) {
this.someList.push(item);
this.isShowModal = false;
}
}
};
</script>
I understand the .sync modifier returned in Vue 2.3, and am using it for a simple child component which implements a 'multiple-choice' question and answer. The parent component calls the child like this:
<question
:stem="What is your favourite colour?"
:options="['Blue', 'No, wait, aaaaargh!']
:answer.sync="userChoice"
>
The parent has a string data element userChoice to store the result from the child component. The child presents the question and radio buttons for the options. The essential bits of the child look like this (I'm using Quasar, hence q-radio):
<template>
<div>
<h5>{{stem}}</h5>
<div class="option" v-for="opt in options">
<label >
<q-radio v-model="option" :val="opt.val" #input="handleInput"></q-radio>
{{opt.text}}
</label>
</div>
</div>
</template>
export default {
props: {
stem: String,
options: Array,
answer: String
},
data: () => ({
option: null
}),
methods: {
handleInput () {
this.$emit('update:answer', this.option)
}
}
}
This is all working fine, apart from the fact that if the parent then changes the value of userChoice due to something else happening in the app, the child doesn't update the radio buttons. I had to include this watch in the child:
watch: {
answer () {
this.option = this.answer
}
}
But it feels a little redundant, and I was worried that emitting the event to update the parent's data would in fact cause the child 'watch' event to also fire. In this case it would have no effect other than wasting a few cycles, but if it was logging or counting anything, that would be a false positive...
Maybe that is the correct solution for true 2-way binding (i.e. dynamic Parent → Child, as well as Child → Parent). Did I miss something about how to connect the 'in' and 'out' data on both sides?
In case you're wondering, the most common case of the parent wanting to change 'userChoice' would be in response to a 'Clear Answers' button which would set userChoice back to an empty string. That should have the effect of 'unsetting' all the radio buttons.
Your construction had some oddities that didn't work, but basically answer.sync works if you propagate it down to the q-radio component where the changing happens. Changing the answer in the parent is handled properly, but to clear values, it seems you need to set it to an object rather than null (I think this is because it needs to be assignable).
Update
Your setup of options is a notable thing that didn't work.
I use answer in the q-radio to control its checked state (v-model has special behavior in a radio, which is why I use value in conjunction with v-model). From your comment, it looks like q-radio wants to have a value it can set. You ought to be able to do that with a computed based on answer, which you would use instead of your option data item: the get returns answer, and the set does the emit. I have updated my snippet to use the val prop for q-radio plus the computed I describe. The proxyAnswer emits an update event, which is what the .sync modifier wants. I also implemented q-radio using a proxy computed, but that's just to get the behavior that should already be baked-into your q-radio.
(What I describe is effectively what you're doing with a data item and a watcher, but a computed is a nicer way to encapsulate that).
new Vue({
el: '#app',
data: {
userChoice: null,
options: ['Blue', 'No, wait, aaaaargh!'].map(v => ({
value: v,
text: v
}))
},
components: {
question: {
props: {
stem: String,
options: Array,
answer: String
},
computed: {
proxyAnswer: {
get() {
return this.answer;
},
set(newValue) {
this.$emit('update:answer', newValue);
}
}
},
components: {
qRadio: {
props: ['value', 'val'],
computed: {
proxyValue: {
get() {
return this.value;
},
set(newValue) {
this.$emit('input', newValue);
}
}
}
}
}
}
},
methods: {
clearSelection() {
this.userChoice = {};
}
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.min.js"></script>
<div id="app">
<question stem="What is your favourite colour?" :options="options" :answer.sync="userChoice" inline-template>
<div>
<h5>{{stem}}</h5>
<div class="option" v-for="opt in options">
<div>Answer={{answer && answer.text}}, option={{opt.text}}</div>
<label>
<q-radio :val="opt" v-model="proxyAnswer" inline-template>
<input type="radio" :value="val" v-model="proxyValue">
</q-radio>
{{opt.text}}
</label>
</div>
</div>
</question>
<button #click="clearSelection">Clear</button>
</div>