Vuetify: v-dialog won't close although v-model variable is set to false - vue.js

I have a couple of dialogs which are created with v-for (exchangeTypeAbbreviation and exchangeType come from there). When I click on the activator button, the dialog opens and the value in the object I use for storing the dialogs' state is updated to "true".
But when I click the cancel or save button, the dialog won't close, although the object's value is updated to "false".
<v-list-item>
<v-dialog
max-width="400"
v-model="dialogs[exchangeTypeAbbreviation]"
>
<template v-slot:activator="{ on }">
<v-list-item v-on="on">
<v-icon class="pr-4">
mdi-plus
</v-icon>
Add Product Flow
</v-list-item>
</template>
<v-card>
<v-card-title>Add Product Flow</v-card-title>
<v-card-subtitle
v-text="exchangeType"
></v-card-subtitle>
<v-card-actions>
<v-btn
#click="
dialogs[exchangeTypeAbbreviation] = false;
createUnitProcessExchange(
exchangeTypeAbbreviation
);
"
>Save</v-btn
>
<v-btn
#click="dialogs[exchangeTypeAbbreviation] = false"
>Cancel</v-btn
>
</v-card-actions>
</v-card>
</v-dialog>
</v-list-item>
<script>
export default {
name: 'Activities',
data: () => ({
dialogs: {},
exchangeTypes: {},
unitProcessExchangesOptions: null,
}
}),
mounted() {
Promise.all([
this.loadUnitProcessExchangeOptions()
])
},
methods: {
async loadUnitProcessExchangeOptions() {
return this.$api
.options('/unitprocessexchanges/', {
headers: {
Authorization: 'Token ' + localStorage.getItem('token')
}
})
.then(response => {
this.unitProcessExchangesOptions = response.data.actions.POST
for (const exchangeType of this.unitProcessExchangesOptions
.exchange_type.choices) {
this.exchangeTypes[exchangeType.value] = exchangeType.display_name
this.dialogs[exchangeType.value] = false
}
})
},
async createUnitProcessExchange(exchangeTypeAbbreviation) {
this.newUnitProcessExchange.activity = this.activities[
this.selectedActivity
].url
this.newUnitProcessExchange.exchange_type = exchangeTypeAbbreviation
this.dialogs[exchangeTypeAbbreviation] = false
// eslint-disable-next-line no-debugger
debugger
}
}
}
</script>

I was able to figure out why it doesn't work. Due to limitations in JavaScript, Vue.js has some difficulties to observe changes in Objects and Arrays. This is documented here.
In my case, I added nested variables inside my "dialogs" variable by assigning them directly, e.g. like this
this.dialogs[index] = false
However, this creates a sub-element which can't be tracked by Vue.js. To make sure that changes on this element can be tracked, it either has to be pre-defined from the beginning or needs to be set by using the Vue.$set command. Always using the following command, solved the issue for me:
this.$set(dialogs, index, false)

I think the first problem is you are trying to change the object with an array notation i.e array[0] but it should be a dot notation with object property, in your case it would be dialogs.exchangeTypeAbbreviation = false.
With that one more problem would be that property doesn't exist so in
data: () => ({
dialogs: {exchangeTypeAbbreviation:Boolean},
exchangeTypes: {},
unitProcessExchangesOptions: null,
}
}),
with this now you can set the value of exchangeTypeAbbreviation.

Related

Pass one string piece of data from parent component to child. Vue.js 2

Hoping someone can see a simple mistake I'm making and help me correct it.
I'm trying to pass one string variable as a prop from a parent to a child. This string reveals itself on a checkbox select. There are three and depending which is selected, the name associated will be passed.
Basically, showing some components if different checkboxes are checked. I can clearly see the variable I'm passing shows up in the parent component just fine. I log it out in the method provided. However, it doesn't pass to the child component. I log out there and get undefined as the result.
I've tried multiple solutions, and read about passing props, but nothing is working.
Parent component looks like this.
<template>
<v-col>
<v-checkbox
label="LS"
color="primary"
value="ls"
v-model="checkedSensor"
#change="check($event)"
hide-details
/></v-checkbox>
</v-col>
<v-col cols="2" class="mx-auto">
<v-checkbox
label="DG"
color="primary"
value="dg"
v-model="checkedSensor"
#change="check($event)"
hide-details
/>
</v-col>
<v-col cols="2" class="mx-auto">
<v-checkbox
label="CR"
color="primary"
value="cr"
v-model="checkedSensor"
#change="check($event)"
hide-details
/>
<ls-sensor v-if="lsSensor" :sensorType="checkedSensor" />
</template>
<script>
export default{
data() {
return {
checkedSensor: " ",
lsSensor: false,
dgSensor: false,
crSensor: false,
};
},
methods: {
check: function (e) {
this.showDeviceComponent(e);
},
showDeviceComponent(e) {
if (e == "ls") {
this.lsSensor = true;
this.crSensor = false;
this.dgSensor = true;
console.log("file input component", this.checkedSensor)
} else if (e == "dg") {
this.dgSensor = true;
this.lsSensor = false;
this.crSensor = false;
} else {
this.crSensor = true;
this.dgSensor = false;
this.lsSensor = false;
}
},
},
}
</script>
Child component (just putting the script here as I don't have it's place in the template yet. In the mounted method, I should be seeing the value from the prop. It's showing up as undefined. Gahh.. what silliness I have made a mistake on? Your help is greatly appreciated.
export default {
props:['sensorType'],
data() {
return {
coating: false,
};
},
mounted() {
console.log("required input component, sensor type", this.sensorType)
},
components: {
coatings: require("#/components/shared/FormData/Coatings.vue").default,
"ls-sensor-panel": require("#/components/shared/FormData/LS_SensorPanel.vue").default,
},
};
The only thing that stands out to me is when you create camel cased property names, I am pretty sure that those have to be written as dash (-) separated attributes on a component?
<ls-sensor v-if="lsSensor" :sensor-type="checkedSensor" />
So prop: ['sensorType'] is passed as :sensor-type=""

Update data from local copy of Vuex store

I am implementing a user profile edit page that initially consists of the data loaded from the vuex store. Then the user can freely edit his data and finally store them in the store.
Since the user can also click the cancel button to revert back to his original state, I decided to create a 'local' view copy of the user data fetched from the store. This data will be held in the view and once the user presses save, they will be saved in the store.
The view looks as following:
<template class="user-profile">
<v-form>
<template v-if="profile.avatar">
<div class="text-center">
<v-avatar width="120" height="120">
<img
:src="profile.avatar"
:alt="profile.firstname"
>
</v-avatar>
</div>
</template>
<div class="text-center mt-4">
<v-btn
color="primary"
dark
#click.stop="showImageDialog=true"
>
Change Image
</v-btn>
</div>
<v-row>
<v-col>
<v-text-field
label="First name"
single-line
disabled
v-model="profile.firstname"
></v-text-field>
</v-col>
<v-col>
<v-text-field
label="Last name"
single-line
disabled
v-model="profile.lastname"
></v-text-field>
</v-col>
</v-row>
<v-text-field
label="Email"
single-line
v-model="profile.email"
></v-text-field>
<v-text-field
id="title"
label="Title"
single-line
v-model="profile.title"
></v-text-field>
<v-textarea
no-resize
clearable
label="Biography"
v-model="profile.bio"
></v-textarea>
<v-dialog
max-width="500"
v-model="showImageDialog"
>
<v-card>
<v-card-title>
Update your profile picture
</v-card-title>
<v-card-text>
<v-file-input #change="setImage" accept="image/*"></v-file-input>
<template v-if="userAvatarExists">
<vue-cropper
ref="cropper"
:aspect-ratio="16 / 9"
:src="profile.avatar"
/>
</template>
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn
color="green darken-1"
text
#click="showImageDialog=false"
>
Cancel
</v-btn>
<v-btn
color="green darken-1"
text
#click="uploadImage"
>
Upload
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<div class="mt-8">
<v-btn #click="onUpdateUser">Update</v-btn>
</div>
</v-form>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import VueCropper from 'vue-cropperjs';
import 'cropperjs/dist/cropper.css';
export default {
components: { VueCropper},
mounted() {
this.profile = this.getUserProfile ? this.getUserProfile : {}
},
data() {
return {
profile: {},
avatar: null,
userAvatarExists: false,
showImageDialog: false,
}
},
watch: {
getUserProfile(newData){
this.profile = newData;
},
deep: true
},
computed: {
...mapGetters({
getUserProfile: 'user/me',
})
},
methods: {
...mapActions({
storeAvatar: 'user/storeAvatar',
updateUser: 'user/update'
}),
onUpdateUser() {
const data = {
id: this.profile.id,
email: this.profile.email,
title: this.profile.title,
bio: this.profile.bio,
avatar: this.profile.avatar,
}
this.updateUser(data)
},
uploadImage() {
this.$refs.cropper.getCroppedCanvas().toBlob((blob => {
this.storeAvatar(blob).then((filename => {
this.profile.avatar = filename.data
this.$refs.cropper.reset()
}));
this.showImageDialog = false
}));
},
setImage(file) {
this.userAvatarExists = true;
if (file.type.indexOf('image/') === -1) {
alert('Please select an image file');
return;
}
if (typeof FileReader === 'function') {
const reader = new FileReader();
reader.onload = (event) => {
this.$refs.cropper.replace(event.target.result);
};
reader.readAsDataURL(file);
} else {
alert('Sorry, FileReader API not supported');
}
}
}
}
</script>
Issues/Questions:
As you can see from the code, after the user changes his profile
picture, the image should be rendered based on the
v-if="profile.avatar". The issue is that after the
profile.avatar is set in the uploadImage function, the
template does not see this change and no image is rendered.
However if I change the code so that the profile.avatar becomes
just avatar (it is no longer within the profile object), the
template starts to see the changes and renders the image
correctly. Why so? Does it have something to do with making a
copy from the store in the watch function?
Is it in general a good approach to keep the profile just as a local
view state or should it rather be stored in the vuex store even if
it is just a temporary data?
As you can see in the mounted function, I am setting the profile
value based on the getUserProfile getter. This is because the
watch function does not seem to be called again when switching
routes. Is there any other way how to do this?
The issue is due to the reactivity of data properties
You have used profile as an object, default it doesn't have any properties like avatar or firstname, its just empty
In vue js, If you are declaring an object, whatever the key mention in the declaration is only the part of reactivity. Once the keys inside profile changes, it rerenders the template
But still you can add new properties to a data property object by using $set
lets say in data you have declared
profile: {}
if you want to set avatar as new reactive property in runtime use
this.$set(this.profile, key, value)
which is
this.$set(this.profile, avatar, imageData)
In your above code, the setIuploadImage function
uploadImage() {
var self = this;
self.$refs.cropper.getCroppedCanvas().toBlob((blob => {
self.storeAvatar(blob).then((filename => {
self.$set(self.profile, "avatar", filename.data)
self.$refs.cropper.reset()
}));
self.showImageDialog = false
}));
},
this won't work inside arrow function in vuejs, so just preserved the this inside another variable "self" and used inside arrow function
Also in mounted function, if this.getUserProfile returns empty object, then as per javascript empty object is always truthy and directly assigning object to profile doesn't make the object reactive
mounted() {
this.profile = this.getUserProfile ? this.getUserProfile : {}
},
above code can be written as
mounted() {
if (this.getUserProfile && Object.keys(this.getUserProfile).length) {
var self = this;
Object.keys(this.getUserProfile).map(key => {
self.$set(self.profile, key, self.getUserProfile[key])
});
} else {
this.profile = {};
}
}

how to detect change of actual value not just OnChange nuxt vuetify

As a result of
export default {
name: "Details",
async asyncData({ redirect, params, store }) {
if (
!store
I am returning a few values in which one of them is
return {
camera: c,
thumbnail_url: thumbnail_url,
camera, and then in my form fields where I am populating a Vuetify dialog, Text Field inputs
such as
<v-dialog v-model="dialog" max-width="600px">
<v-card>
<v-card-text>
<v-layout class="model-container">
<v-row>
<v-col cols="12" lg="7" md="7" sm="12" xs="12">
<v-text-field
v-model="camera.name"
class="caption bottom-padding"
required
>
<template v-slot:label>
<div class="caption">
Name
</div>
</template>
</v-text-field>
my issue is, I have a button as
<v-btn color="primary" text #click="updateCamera">
Save
</v-btn>
which I only want to make disable false, only if there is an actual change occurs to, this.camera, in updateCamera method, I can use the updated values as
async updateCamera() {
let payload = {
name: this.camera.name,
but I want to enable or disable the button on when change occurs,
I had tried #input, I have also tried to watch camera object
<v-text-field
v-model="camera.name"
class="caption bottom-padding"
required
#input="up($event, camera)"
>
This way I tried to get some info about event, such as which text field it is, so I can compare, but in up method it only passes input value.
in watch
camera: function() {
this.$nextTick(() => {
console.log(this.camera)
})
}
camera: {
handler: function(val) {
this.$nextTick(() => {
console.log(val)
})
/* ... */
},
immediate: true
}
I have tried this but nothing worked.
Of course, we can enable or disable a button on change but not just if the user places an A and then deletes it, not such change.
Any help would be wonderful
Update:
Even after using this
camera: {
handler: function(newValue) {
if (newValue === this.dumpyCamera) {
console.log(this.dumpyCamera)
console.log(newValue)
console.log("here")
this.updateButton = true
} else {
this.updateButton = false
}
},
deep: true
}
both new and old values are the same.
I have tried to add new variable dumyCamera and on mount I have assigned this.camera value to this.dumyCamera but when something changes in camera, it changes this.dumyCamera as well? why is this the case?
You should be able to recognize any changes made to this.camera by using a watcher
watch: {
camera: {
handler (newValue, oldValue) {
// do something here because your this.camera changed
},
deep: true
}
}

Dynamically update class based on individual form elements validation in Vuetify

Take a look at the official Vuetify form validation example.
The very first example, if you click in a field and then outside it, it is automatically validated. The entire field becomes red and you get a hint in red text.
What I would like is based on that built-in/native validation to add or remove a class (that turns the text red) on a completely separate HTML element.
It would be ideal if something like hint-for="" exists. Some way to connect a separate HTML element with the form field validation.
I have tried to condition the class with the "valid" property of the form element, something like this: this.$refs.form.$children[1].valid but this doesn't exist on page load and throws errors.
Right now I have some results by basically having double validation, the normal one that validates automatically based on the "rules" property on the form field, and a custom one that I call my self on #input and on #blur of the form field, but this is largely inefficient so I'm hoping there's a better way.
You can use the value of the v-form to track the validity of your form. In order to listen to changes you can use the input event like this
<template>
<div>
<v-form lazy-validation v-model="valid" #input="updateOtherElement">
<v-text-field
v-model="email"
:rules="emailRules"
label="Email"
required
></v-text-field>
</v-form>
</div>
</template>
<script>
export default {
data () {
return {
valid: true,
email: "",
emailRules: [
v => /.+#.+/.test(v) || 'E-mail must be valid',
],
}
},
methods: {
updateOtherElement(valid) {
// update other elements css
}
}
}
</script>
An alternative would be to track the changes with a watcher
This is what I came up with.
I had some trouble with validation being active immediately and nonexistent text fields on page load but with this setup, it works.
So once validation kicks in the fields will turn red by the native Vuetify validation if they are not valid, and I toggle the "invalid" class on a completely separate piece of HTML with custom functions. What is important here that each text field has it's own "subheader" which will turn red only if that single connected text-filed is invalid, not the entire form.
<template>
<v-form
ref="form"
lazy-validation
>
<v-subheader v-bind:class="passwordValid()">
Password *
</v-subheader>
<v-text-field
:rules="rules.password"
ref="password"
></v-text-field>
<v-subheader v-bind:class="passwordAgainValid()">
Password Again *
</v-subheader>
<v-text-field
:rules="rules.passwordAgain"
ref="passwordAgain"
></v-text-field>
</v-form>
<v-btn
v-on:click="save"
>
Save
</v-btn>
</template>
<script>
export default {
methods: {
save() {
let self = this
self.activateRules()
self.$nextTick(function () {
if (self.$refs.form.validate()) {
self.rules = {}
// submit...
}
})
},
activateRules () {
this.rules = {
password: [
v => v.length > 0 || ''
],
passwordAgain: [
v => v.length > 0 || ''
]
}
},
passwordValid: function () {
let passwordValid = true
if (this.$refs.password) {
passwordValid = this.$refs.password.valid
}
return {
'error--text': !passwordValid
}
},
passwordAgainValid: function () {
let passwordAgainValid = true
if (this.$refs.passwordAgain) {
passwordAgainValid = this.$refs.passwordAgain.valid
}
return {
'error--text': !passwordAgainValid
}
}
}
}
</script>

How can I call ajax before display datepicker in vuetify?

Look at this : https://codepen.io/positivethinking639/pen/mddejJN
My script of vue like this :
data: () => ({
modalTest: false,
dateTest: null,
time: null,
allowedTimes: ['8:30 am','9:00am','10:30am','1:30pm','3:30 pm']
}),
methods: {
saveData() {
this.$refs.dialogTest.save(this.dateTest)
},
allowedDates: val => parseInt(val.split('-')[2], 10) % 2 === 0,
setTime(time) {
this.time = time
}
I want before call datepicker, I call ajax first
How can I do it?
#Max proposal is not fully answers the question.
Let's add new data property which will trigger the show of calendar component:
isAjaxCompl: false,
Move the button out of template to directly change dialog v-model:
<v-btn color="success" #click="openDialog()">call date</v-btn>
Make the function which will be fired on dialog open:
openDialog() {
this.modalTest = true;
axios.get('https://reqres.in/api/users?delay=1').then((response) => {
this.isAjaxCompl = true;
})
},
Finally, add v-if which will show calendar component only when axios get the response:
<v-date-picker v-if="isAjaxCompl" v-model="dateTest" scrollable :allowed-dates="allowedDates">
Link to the corresponding CodePen:
https://codepen.io/RobbyFront/pen/RwwWewM
You need to move the dialog button outside and add a #click method for showing the dialog
Your Code
<template v-slot:activator="{ on }">
<v-btn color="success" dark v-on="on">call date</v-btn>
</template>
New Code
Html
<v-btn color="success" dark #click="showDate">call date</v-btn>
Code
showDate(){
console.log("Ajax calling");
this.modalTest = true;
}
Here the pen