Cannot read property 'focus' of undefined in VUE When setting focus to button - vue.js

I am new to vue I have component which if the endpoint fails, calls my generic 'Error' modal. All this is working fine but I keep getting the following error:
Cannot read property 'focus' of undefined
This only happens for the else part of my method function.
For this specific issue is I my 'failedPrcess' equals any of the following, this is when I get is, all others are fine:
existOrderSearchProdOrders
stockSearchStockLevels
cartFetchCouriers
Code
<template>
<div class="modal fade danger-modal" id="errorModal" tabindex="-1" role="dialog" aria-labelledby="errorModalTitle" aria-hidden="true"
data-keyboard="false" data-backdrop="static" style="z-index: 99999">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content danger-modal-content">
<div class="modal-header danger-modal-headerfooter">An error has occurred</div>
<div class="modal-body">
<p v-if="failedProcess === 'appGetAccount' || failedProcess === 'existOrderSearchProdOrders' || failedProcess === 'stockSearchStockLevels'
|| failedProcess === 'cartFetchCouriers'">
{{ contactTxt | capitalize }}
</p>
<p v-else-if="errorCount < 3">If the error continues, {{ contactTxt }}</p>
<p v-else>As the error has continued, {{ contactTxt }}</p>
<p>
<b>
01234 567890
<br />
Open from 00:00 to 07:00
</b>
</p>
<p>Advising of what you were doing when the error occurred.</p>
</div>
<div class="modal-footer danger-modal-headerfooter">
<a v-if="failedProcess === 'appGetAccount'" ref="logoutButton" class="btn btn-primary" :class="logoutButtClicked" #click="logoutClicked = true" href="/site/logout">
<span v-if="!logoutClicked" id="logoutButtonLabel">Logout</span>
<span v-else id="logoutSpinner">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Logging out
</span>
</a>
<router-link v-else-if="failedProcess === 'fetchOrderReportDetails'" to="/review" tag="button"
ref="existOrdersButton" class="btn btn-primary" type="button" data-dismiss="modal" #click.native="closeButton">
Return to existing orders
</router-link>
<button v-else-if="errorCount < 3 && (failedProcess !== 'productsFetchProducts' && failedProcess !== 'existOrderSearchProdOrders'
&& failedProcess !== 'stockSearchStockLevels' && failedProcess !== 'cartFetchCouriers')" ref="closeButton" class="btn btn-primary"
type="button" data-dismiss="modal" #click="closeButton">
Close
</button>
<router-link v-else to="/" tag="button" ref="homeButton" class="btn btn-primary" type="button" data-dismiss="modal" #click="closeButton">
Return to homepage
</router-link>
</div>
</div>
</div>
</div>
</template>
<script>
import * as params from '../params';
export default {
name: "ErrorModal",
data() {
return {
contactTxt: 'please contact us on:',
errorCount: 0,
failedProcess: '',
}
},
mounted() {
VueEvent.$on('show-error-modal', (failedProcess) => {
if (this.failedProcess !== failedProcess) {
this.errorCount = 0;
}
this.failedProcess = failedProcess;
$('#errorModal').modal('show').on('shown.bs.modal', this.focus);
});
},
methods: {
focus() {
if (this.failedProcess === 'appGetAccount') {
this.$refs.logoutButton.focus();
} else if (this.failedProcess === 'fetchOrderReportDetails') {
this.$refs.existOrdersButton.$el.focus();
} else if (this.errorCount < 3 && this.failedProcess !== 'productsFetchProducts') {
this.$refs.closeButton.focus();
} else {
this.$refs.homeButton.$el.focus();
}
},
}
}
</script>`enter code here`

I've tried using v-if before and I also had similar problems and the best solution I found was, instead of using v-if/v-else-if/v-else, use v-show instead to perform conditional rendering.
Also, as the Vue.js doc says:
Generally speaking, v-if has higher toggle costs while v-show has higher initial render costs. So prefer v-show if you need to toggle something very often, and prefer v-if if the condition is unlikely to change at runtime.

Related

Vue's reactivity not triggered when using Bootstrap 5's alert div

Vue's reactivity not triggered when using Bootstrap 5's alert div.
See my code:
<template>
<div>
<div
v-if="alertICDMsg!==''"
id="alertICDCode"
class="alert alert-info alert-dismissible fade show"
role="alert"
>
<i class="fa-solid fa-lightbulb" />
<strong> Note!</strong> <span v-html="alertICDMsg" />
<button
type="button"
class="btn-close"
data-bs-dismiss="alert"
aria-label="Close"
/>
</div>
<div class="input-group mb-3">
<div class="col-xs-1">
<input
id="ICDCode"
v-model="editing_icdCode"
class="form-control"
placeholder="ICD Code"
aria-label="ICD Code"
#input="ICDCodeSearchRequested"
>
</div>
<input
id="Diagnosis"
v-model="editing_diagnosis"
type="text"
class="form-control"
placeholder="Diagnosis"
aria-label="Diagnosis"
aria-describedby="basic-addon1"
list="icdsearchlist"
#change="SelectedDiagnosisTextOption"
#input="ICDTextSearchRequested"
>
<datalist id="icdsearchlist">
<option
v-for="(disease_option, index) in icd_diagnosis_options"
:key="index"
>
{{ disease_option }}
</option>
</datalist>
<button
id="btnAddDiagnoses"
href="#"
class="btn btn-primary mx-1"
#click="AddDiagnosis"
>
<i class="fal fa-plus-circle" />
</button>
<button
id="btnCopyPreviousDiagnoses"
href="#"
class="btn btn-primary BtnSaveGroup mx-1"
>
<i class="far fa-history" />
</button>
<button
id="quickbill"
class="btn btn-primary mx-1"
>
<i class="fas fa-search-plus" />
</button>
<button
id="clearICD"
class="btn btn-danger mx-1"
#click="ClearICDFields"
>
<i class="fad fa-times-circle" />
</button>
</div>
</div>
<template>
<script>
export default {
data() {
return {
alertICDMsg:"",
};
},
watch: {
alertICDMsg: {
handler(val) {
console.log(`Val for alertICDMsg changed to :${val}`);
},
immediate: true,
deep: true,
},
},
methods: {
ICDCodeSearchRequested() {
console.log(`Search by ICD code`);
this.alertICDMsg="Searching in ICD Code box will search only by code. To search by a diagnosis name, type in the Diagnosis box."
console.log(`alertICDMsg is ${this.alertICDMsg}`);
setTimeout(function() {
console.log(`Dismissing alert`);
this.alertICDMsg='';
console.log(`alertICDMsg is ${this.alertICDMsg}`);
}, 5000);
},
},
}
</script>
Console log:
Search by ICD code
SubClinicalBlock.vue?d801:291 alertICDMsg is Searching in ICD Code box will search only by code. To search by a diagnosis name, type in the Diagnosis box.
SubClinicalBlock.vue?d801:220 Val for alertICDMsg changed to :Searching in ICD Code box will search only by code. To search by a diagnosis name, type in the Diagnosis box.
SubClinicalBlock.vue?d801:293 Dismissing alert
SubClinicalBlock.vue?d801:298 alertICDMsg is
The problem is that after 5 seconds, though the value of the variable changes, the alert is still visible.
I checked some similiar questions, and have seen this happening when bootstrap's javascript wasnt loaded. But for me, Bootstrap v5.0.1 JS is being loaded from the CDN and appears in the sources tab in Chrome.
Try to change the function inside of setTimeout to arrow function like this
setTimeout(() => { // code here })
The this inside of setTimeout(function () => {}) reference to the wrong context (the function itself) instead of the Vue component.
The arrow function doesn't have the this binding so when you use the arrow function the this keyword will reference the Vue component and change the state.
More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Why still adding even with validation form?

When I click the button on my modal with an empty field on my input its give me an undefined value on my console. And when I put a value on my input and click the button it is adding to my database. The problem is even the empty field or the undefined value are also adding to my database and the sweetalert is not working. I want to prevent the empty field adding to my database and prevent the undefined. Can somebody help me?
//start of method
checkForm: function(e) {
if (this.category_description) {
return true;
}
this.errors = [];
if (!this.category_description) {
this.errors.push('Category required.');
}
e.preventDefault();
},
addCategory : function() {
axios({
method : "POST",
url : this.urlRoot + "category/add_category.php",
data : {
description : this.category_description
}
}).then(function (response){
vm.checkForm(); //for FORM validation
vm.retrieveCategory();
console.log(response);
swal("Congrats!", " New category added!", "success");
vm.clearData();
}).catch(error => {
console.log(error.response);
});
},
//end of method
<form id="vue-app" #submit="checkForm">
<div class="modal" id="myModal" > <!-- start add modal -->
<div class="modal-dialog">
<div class="modal-content " style="height:auto">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title"> Add Category </h4>
<button #click="clearData" type="button" class="close" data-dismiss="modal"><i class="fas fa-times"></i></button>
</div>
<!-- Modal body -->
<div class="modal-body">
<div class="form-group">
<div class="col-lg-12">
<input type="text" class="form-control" id="category_description" name="category_description" v-model="category_description" placeholder="Enter Description">
<p v-if="errors.length">
<span v-for="error in errors"> {{ error }} </span>
</p>
</div>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="submit"#click="category_description !== undefined ? addCategory : ''" class="btn btn-primary"> Add Category </button>
</div>
</div>
</div>
</div>
</form>
The easiest way to stop this is adding data check. And condition check at top of your method.category_description !== undefined. Btw, move your e.preventDefault() to top too.
First of all do this:
- <button type="submit" #click="category_description !== undefined ? addCategory : ''" class="btn btn-primary"> Add Category </button>
+ <button type="submit" #click.prevent="addCategory" class="btn btn-primary"> Add Category </button>
and then in addCategory:
addCategory() {
if (!this.category_description) {
return;
} else {
// do your stuff here
}
}
When you are clicking on Add Category button, it is triggering the addCategory along with your validation method.
The return value of validation method has no impact on triggering of addCategory.
This issue can be handled in following ways.
Call addCategory only when there is some valid data
<button type="submit" #click="category_description != undefined ? addCategory() : ''" class="btn btn-primary"> Add Category </button>
Call the validation method inside addCategory and then proceed.

Data Reactivity On Post Request Vue

Im having issues with my data not reacting correctly when a new object is added to the array of data. I am currently looping through an array of engagements that belong to a client like this
<div class="row mx-2 px-2 justify-content-between" v-if="!engagementLoaded">
<div class="card mb-3 shadow-sm col-lg-5 col-md-3 p-0" v-for="(engagement, index) in engagement" :key="index">
<div class="d-flex justify-content-between card-header">
<h3 class="m-0 text-muted">{{ index + 1 }}</h3>
<h5 class="align-self-center m-0"><span>Return Type: </span> {{ engagement.return_type }} </h5>
</div>
<div class="card-body text-left p-0 my-1">
<h5 class="p-4"><span>Year: </span> {{ engagement.year }} </h5>
<hr class="my-1">
<h5 class="p-4"><span>Assigned To: </span> {{ engagement.assigned_to }} </h5>
<hr class="my-1">
<h5 class="p-4"><span>Status: </span> {{ engagement.status}} </h5>
</div>
<div class="card-footer d-flex justify-content-between">
<router-link to="#" class="btn">View</router-link>
<router-link to="#" class="btn">Edit</router-link>
</div>
</div>
</div>
Everything works fine until I add a new engagement to the array. My AddEngagement Component is seperate but this is the form and script for it.
<form #submit.prevent="addEngagement" class="d-flex-column justify-content-center">
<div class="form-group">
<select class="form-control mb-3" id="type" v-model="engagement.return_type">
<option v-for="type in types" :key="type.id" :value="type">{{ type }}</option>
</select>
<input type="text" class="form-control mb-3" placeholder="Year" v-model="engagement.year">
<input type="text" class="form-control mb-3" placeholder="Assign To" v-model="engagement.assigned_to">
<input type="text" class="form-control mb-3" placeholder="Status" v-model="engagement.status">
<div class="d-flex justify-content-between">
<button type="submit" class="btn btn-primary d-flex justify-content-start">Create</button>
<router-link v-bind:to="'/client/' +client.id+ '/engagements'" class="btn btn-secondary float-right">Dismiss</router-link>
</div>
</div>
</form>
This is the addEngagement Method for the form
methods: {
addEngagement(e) {
if(!this.engagement.return_type || !this.engagement.year ){
return
} else {
this.$store.dispatch('addEngagement', {
id: this.idForEngagement,
client_id: this.client.id,
return_type: this.engagement.return_type,
year: this.engagement.year,
assigned_to: this.engagement.assigned_to,
status: this.engagement.status,
})
e.preventDefault();
}
e.preventDefault();
this.engagement = ""
this.idForEngagement++
this.$router.go(-1);
},
},
I think the issue is happening here but im not sure
this.$router.go(-1);
Ive tried this as well
this.$router.push({path: 'whatever route'})
and it did not change either
Somehow I need the parent component EngagementsList to react correctly to my newly added engagement that is submitted from the AddEngagement componenet if that makes sense..
here is the code for the addEngagement in the Vuex
addEngagement(context, engagement) {
axios.post(('/engagements'), {
client_id: engagement.client_id,
return_type: engagement.return_type,
year: engagement.year,
assigned_to: engagement.assigned_to,
status: engagement.status,
done: false
})
.then(response => {
context.commit('getClientEngagement', response.data)
})
.catch(error => {
console.log(error)
})
},
Although I can't see your code, I'm pretty certain I know the problem. You have an array but it's not reactive to the objects within. This is because Vue doesn't know to observe this array.
If you want your array to be reactive, use Vue.set from within your store model.
Vue.set(this/state, 'array_name', Array<Of objects>)
This will make sure vue watches for changes within the Array.
For your use case, you will need to append the engagement object to the existing array and then use that array:
const engagements = state.engagements
engagements.push(engagement)
Vue.set(state, 'engagements', engagements)
So i've tried different configurations of this. I changed my state description that the v-for is iterating to clientengagements
engagement now equals clientengagements
here is the mutation currently
getClientEngagements(state, engagement, clientengagements) {
state.clientengagements = clientengagements
clientengagements.push(engagement)
Vue.set(state, 'clientengagements', clientengagements)
},
Which is not working. Ive also tried
getClientEngagements(state, clientengagements) {
state.clientengagements = clientengagements
clientengagements.push(engagement)
Vue.set(state, 'clientengagements', clientengagements)
},
Which will tell me that "engagement" is not defined
If anyone is still able to help this is the Action
addEngagement(context, engagement) {
axios.post(('/engagements'), {
client_id: engagement.client_id,
return_type: engagement.return_type,
year: engagement.year,
assigned_to: engagement.assigned_to,
status: engagement.status,
done: false
})
.then(response => {
context.commit('getClientEngagements', response.data)
})
.catch(error => {
console.log(error)
})
},
The response.data is mutating my clientengagements array to just a single object of the newly added engagement..
context.commit('getClientEngagements`, response.data)
Is commiting to this mutation
getClientEngagements(state, engagement, clientengagements) {
state.clientengagements = clientengagements
clientengagements.push(engagement)
Vue.set(state, 'clientengagements', clientengagements)
},

How to set class to child element inside v-for loop

I need some help, I have v-for loop which outputs elements of array referenceDetailsDocumentsData, I need to check at the same time if the id of this element exists in another array documentsData, in this case I need to add custom class to child of this element.
<div class="loading-doc-item"
v-for="referenceDetails in referenceDetailsDocumentsData"
:key="referenceDetails.id">
<div class="loading-doc-show">
{{ referenceDetails.name }}
<span class="upload-status" v-if="checkUploadedDocuments(referenceDetails.id)">
<i class="fa fa-check-circle"></i>
</span>
<span class="upload-status" v-else>
<i class="fa fa-check"></i>
</span>
</div>
</div>
methods() {
checkUploadedDocuments(id) {
return this.documentsData.filter(item => item.id === id);
}
}
In my case, I am getting an error
Error in render: "TypeError: this.documentsData.filter is not a
function"
Your logic is wrong - the method checkUploadedDocuments will return Array but it must return Boolean.
<div class="loading-doc-item"
v-for="referenceDetails in referenceDetailsDocumentsData" :key="referenceDetails.id">
<div class="loading-doc-show">
{{ referenceDetails.name }}
<span class="upload-status">
<i class="fa"
:class="{documentsData && documentsData.length &&
documentsData.findIndex(item => item.id === referenceDetails.id) !== -1
? 'fa-check-circle' : 'fa-check'}"></i>
</span>
</div>
</div>

Add class on click in vuejs

My vue template:
<div
class="col-sm-4 col-xs-6 thumb"
v-for="(photo, index) in photos"
#click.prevent="check(index)"
>
<a class="thumbnail" :class="{'active': photo.checked}">
<img class="img-responsive" :src="photo.picture" alt="">
</a>
</div>
My check() method:
check(index) {
if(!("checked" in this.photos[index]))
this.photos[index].checked = true
else
this.photos[index].checked = !this.photos[index].checked
},
Everything seems correct but it's not working. What could the problem be?
Vue cannot detect changes to an index of an array.
Get a reference to the photo object of the index passed to check() and then use Vue.set() to update the array like so:
check(index) {
let photo = this.photos[index];
if (!("checked" in photo)) {
photo.checked = true
} else {
photo.checked = !photo.checked
}
Vue.set(this.photos, index, photo);
},
Here's a fiddle.
How about just #click.prevent="$set(photo, 'checked', !photo.checked)" and forget the handler?
<div class="col-sm-4 col-xs-6 thumb" v-for="(photo, index) in photos"
#click.prevent="$set(photo, 'checked', !photo.checked)">
<a class="thumbnail" :class="{'active': photo.checked}">
<img class="img-responsive" :src="photo.picture" alt="">
</a>
</div>
If you want to use the handler:
<div class="col-sm-4 col-xs-6 thumb" v-for="(photo, index) in photos"
#click.prevent="check(photo)">
And
check(photo) {
this.$set(photo, 'checked', !photo.checked)
},