sorry I am here again , I can't fix the problem
This is my form input
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input
type="password"
v-model="password"
class="form-control"
id="exampleInputPassword1"
placeholder="請按登入按鈕"
autocomplete="off"
#keyup.enter="login"
data-bs-target="#login"
/>
</div>
this is my function, I imported bootstrap modal.
import { Modal } from 'bootstrap'
login() {
const auth = getAuth();
signInWithEmailAndPassword(auth, this.email, this.password)
.then((userCredential) => {
const user = userCredential.user;
let myModal = new Modal(document.getElementById('login'));
myModal.hide();
Swal.fire({
position: "center",
icon: "success",
title: "登入成功",
showConfirmButton: false,
timer: 1500,
});
this.$router.replace("admin");
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
if (errorCode === "auth/wrong-password") {
// 密碼錯誤提醒
Swal.fire({
position: "center",
icon: "error",
title: "密碼錯誤",
showConfirmButton: false,
timer: 2000,
});
} else {
// 其他錯誤提醒
Swal.fire({
position: "center",
icon: "error",
title: "密碼錯誤或信箱尚未註冊",
showConfirmButton: false,
timer: 2000,
});
}
console.log(error);
});
},
I use this syntax and it works fine elsewhere, wWhen I press enter in the password input box to jump to the admin page, the modal will be hidden, how sould I do ?
let myModal = new Modal(document.getElementById('login'));
myModal.hide();
Related
I am trying to build a like button on vuejs using axios.
I have a mongoDB controller that works perfectly on postman. But i can't make it work in the frontend.
I want to add the userId in the usersLiked array and i want to add 1 in the like counter on click.
And if the user click on an already liked button, i want to take off his userID from the array and do 0 on the like counter.
thats my schema
const postSchema = mongoose.Schema({
userId: { type: String, required: true, ref: "User" },
content: { type: String, required: true, trim: true },
imageUrl: { type: String, trim: true },
likes: { type: Number, default: 0 },
usersLiked: [{ type: String, ref: "User" }],
firstname: {type: String, required: true, trim: true },
lastname: {type: String, required: true, trim: true },
created_at: { type: Date},
updated_at: { type: Date }
});
this is the axios function i tried
likePost() {
const thisPostId = localStorage.getItem("ThisPostId")
axios
.post('http://127.0.0.1:3000/api/post/like/' + thisPostId, {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
})
.then((response) => {
console.log(response.data);
this.$set(this.post, 'usersLiked', this.post.usersLiked !== response?.data?._id)
})
.catch((error) => console.log(error));
}
},
the html
<div v-if="post.usersLiked == user._id">
<div class="like-setup">
<p class="likes">{{ post.likes }} like !</p>
<button v-on:click="likePost(post._id)" style="color: pink" type="submit"
title="Aimer ce post !" class="button">
<font-awesome-icon icon="fa-solid fa-thumbs-up" /> Like !
</button>
</div>
</div>
<div v-else>
<div class="like-setup">
<p class="likes">{{ post.likes }} like !</p>
<button v-on:click="likePost(post._id)" type="submit" title="Aimer ce post !"
class="button">
<font-awesome-icon icon="fa-solid fa-thumbs-up" /> Like !
</button>
</div>
</div>
and this is my data
data() {
return {
posts: [],
post: {
file: "",
content: "",
},
showModal: false,
showModifyPost: false,
user: {
firstname: "",
lastname: "",
_id: "",
},
};
},
Adding a computed function to get the current user's like status can be helpful here.
{
computed: {
myLikeStatus() {
if (!this.user) return false
if (!Array.isArray(this.posts.usersLiked)) return false
return !!this.posts.usersLiked.find(item => item === this.user._id)
}
}
}
With this computed function you should be able to set classes on the like button to show already-liked status.
<button #click="likePost" type="submit" title="Aimer ce post !"
class="button"
:class="{ liked: myLikeStatus }"
>
<font-awesome-icon :icon="`fa-solid fa-thumbs-${myLikeStatus ? 'up' : 'down'}`" /> Like !
</button>
And now in the LikePost method, just assign the response data to the reactive posts variable as:
{
methods: {
likePost() {
const thisPostId = localStorage.getItem("ThisPostId")
axios
.post('http://127.0.0.1:3000/api/post/like/' + thisPostId, {
headers: {
Authorization: "Bearer " + localStorage.getItem("token"),
},
})
.then((response) => {
console.log(response.data);
this.post = response.data
})
.catch((error) => console.log(error));
}
},
}
}
Also, your like count should be reactive the way it is now if the API is returning the correct count.
I'm a little new in Vue.js and currently I am having a problem with radios.
I have a form with different inputs. When I'm submiting the form I create a JSON file with all the form answers:
Instead of this output I want the value of the selected radio to be 'Checked'.
{
"pos_r_1":"Radio 1"
"pos_r_2":"",
"pos_r_3":"",
"pos_r_4":"",
"pos_t_5":"this a test",
}
LIKE THAT:
{
"pos_r_1":"Checked"
"pos_r_2":"",
"pos_r_3":"",
"pos_r_4":"",
"pos_t_5":"this a test",
}
How can I change the value of the radio to 'checked'?
HTML
<v-form class="text-left" name="form" id="form">
<v-radio-group
v-model="checked"
hide-details="auto"
row
>
<v-radio
v-for="radio in group"
:key="radio.id"
:id="radio.id"
:name="radio.id"
:label="radio.text"
:value="radio.text"
/>
</v-radio-group>
<v-text-field
id="pos_t_5"
name="pos_t_5"
label="Text"
v-model="textfield"
/>
<v-btn
class="p-2"
color="primary"
elevation="11"
#click="onSubmit"
>click me</v-btn>
</v-form>
Script
export default Vue.extend({
name: 'Test',
data: function () {
return {
checked: '',
textfield: '',
group: [
{id: 'pos_r_1', text: 'Radio 1'},
{id: 'pos_r_2', text: 'Radio 2'},
{id: 'pos_r_3', text: 'Radio 3'},
{id: 'pos_r_4', text: 'Radio 4'},
],
}
},
onSubmit() {
this.loading = true
const form = document.querySelector('form');
const data = new FormData(form);
let currentObj = this;
let url = '/report/form/store';
axios({
url,
method: 'post',
data,
}) .then(function (response) {
currentObj.output = response.data;
}) .catch( (error) => {
if (error.response && error.response.status === 422){
this.errors = error.response.data.errors;
}
});
}
}
})
I've tried to change the value of the Radios to 'checked' but that doesn't work because then when I click one radio all getting checked.
This is only an example of the form. The form will be big with more that 20 different questions.
Update
This is not the way to do it. I have to manipulate the value of the radios buttons inside a Form Model, where I will save all the form answers. Then I can change the value of the radio to 'checked' easier.
So, radio buttons works as it should to https://developer.mozilla.org/ru/docs/Web/HTML/Element/Input/radio.
If you need to send a request like pos_r_3: Radio 3, you have to do some transformation on it. I'd suggest the code like:
export default Vue.extend({
name: 'Test',
data: function () {
return {
checked: '',
group: [
{id: 'pos_r_1', text: 'Radio 1'},
{id: 'pos_r_2', text: 'Radio 2'},
{id: 'pos_r_3', text: 'Radio 3'},
{id: 'pos_r_4', text: 'Radio 4'},
],
}
},
onSubmit() {
this.loading = true
const form = document.querySelector('form');
const data = new FormData(form);
for (let i = 0; i < this.group.length; i++){
const currentGroup = this.group[i];
data.set(currentGroup.id, currentGroup.text === this.checked ? 'Checked' : '');
}
let currentObj = this;
let url = '/report/form/store';
axios({
url,
method: 'post',
data,
}) .then(function (response) {
currentObj.output = response.data;
}) .catch( (error) => {
if (error.response && error.response.status === 422){
this.errors = error.response.data.errors;
}
});
}
}
I wanna show Modal from fullcalendar using bootstrap-vue. So when I click event on calendar, the modal will be show. But my code does't work.
This is my html code:
<div class="flex-fill bd-highlight col-lg-12">
<div class="card card-default p-3 my-2">
<full-calendar :event-sources="eventSources" :config="calendarConfig"></full-calendar>
</div>
</div>
<div>
<b-modal v-model="modalShow">Hello From Modal!</b-modal>
</div>
This is my vue code:
<script>
export default {
data() {
return {
modalShow: false,
eventId: 0,
eventSources: [
{
events(start, end, timezone, callback) {
axios.get("http://localhost:8000/api/events").then(response => {
callback(response.data.data);
});
},
color: "yellow",
textColor: "black"
}
],
calendarConfig: {
defaultView: "month",
allDaySlot: false,
locale: "id",
buttonText: {
today: "Hari ini",
month: "Bulanan",
week: "Mingguan",
day: "Harian",
list: "Daftar Kegiatan"
},
header: {
left: "prev,next today",
center: "title",
right: "month,agendaWeek,agendaDay list"
},
eventClick: function(view) {
this.modalShow = true;
}
}
};
}
};
</script>
When I console.log(this.modalShow) the value has been change form "false" to "true". But the modal is not showing.
The scope of this is not your vueContext anymore:
eventClick: function(view) {
this.modalShow = true;
}
you can solve this by using bind:
eventClick: function(view) {
this.modalShow = true;
}.bind(this)
Or
eventClick(view) => {
this.modalShow = true;
}
Full explanation is overhere: https://www.w3schools.com/js/js_arrow_function.asp
I try to use vee-validate on a custom component where if nothing selected on submit should show the validation error
the template looks as it follows
<div id="validate" class="container">
<form #submit.prevent="store()" data-vv-scope="time-off" autocomplete="off">
<div class="col-lg-6">
<div class="form-group">
<select2
:options="options"
placeholder='Select...'
v-validate="'required|in:sick, vacation'"
v-model="form.category"
id="categorywidget"
class="form-control">
</select2>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary pull-right">
Send Request
</button>
</div>
</div>
</div>
</form>
</div>
and here is my vue code
Vue.component('Select2', {
props: ['options', 'value', 'id', 'placeholder', 'clear'],
template: '<select><slot></slot></select>',
mounted: function () {
var vm = this
$(this.$el)
.select2({
data: this.options,
placeholder: this.placeholder,
theme: "bootstrap",
width: '100% !important',
dropdownAutoWidth : true,
allowClear: this.clear !== '' ? this.clear : false
})
.val(this.value)
.attr("id", this.id !== null ? this.id : Date.now() + Math.random() )
.trigger('change')
// emit event on change.
.on('change', function () {
vm.$emit('input', $(this).val())
})
},
watch: {
value: function (value) {
// update value
$(this.$el).val(value).trigger('change');
},
options: function (options) {
// update options
$(this.$el).select2({data: options})
}
},
destroyed: function () {
$(this.$el).off().select2('destroy')
}
});
Vue.use(VeeValidate)
new Vue({
el: '#validate',
data: {
form: {
scopes: [],
category: 'null',
daterange: '',
note: ''
},
options: [
{text: 'Vacation', id: 'vacation'},
{text: 'Sick', id: 'sick'},
{text: 'Not ok', id: 'not-ok'},
]
},
methods: {
store: function() {
this.$validator
.validateAll()
.then(function(response) {
alert('is ok!')
// Validation success if response === true
})
.catch(function(e) {
// Catch errors
alert('not ok!')
})
}
}
});
here is a pen what I created
https://codepen.io/anon/pen/gXwoQX?editors=1111
on submit null the validation is passes. what is wrong with this codes
There are issues raised on this subject in github - #590, #592.
None of them lead me to a solution, so I'd suggest a check inside the promise
.then(response => {
if(this.errors.items.length === 0) {
alert('is valid')
} else {
alert('is not valid')
}
A couple of other notes:
See below, catch() is technically the wrong place to handle validation errors, that should be inside the then(response) and when invalid response === false (but not working because of bug).
The catch() is probably for 'I blew up' errors.
.catch(function(e) {
// Catch errors
// alert('not valid') // don't process these here
})
Also this
v-validate="'required|in:sick, vacation'"
should be this (remove space before vacation)
v-validate="'required|in:sick,vacation'"
i have one form that form is open in popup..so i have only 2 fields in that form..after i submit the form i want to display the form values on the same popup(below the form).how can i do that..can any one help me..
here is my vue page:
<el-form :model="ScheduleInterviewForm" :rules="rules" ref="ScheduleInterviewForm" :inline="true">
<el-form-item prop="schedule_datetime">
<el-date-picker
v-model="ScheduleInterviewForm.schedule_datetime"
type="datetime"
size="small"
placeholder="Select Interview date">
</el-date-picker>
</el-form-item>
<el-form-item prop="interview_type_id">
<el-select size="small" v-model="ScheduleInterviewForm.interview_type_id" placeholder="Select Interview Type">
<el-option
v-for="it in interview_types"
:label="it.type"
:value="it.id">
</el-option>
</el-select>
</el-form-item>
<ElButton
type="success"
size="small"
#click="ScheduleInterview('ScheduleInterviewForm', c.hrc_id)">
SCHEDULE INTERVIEW
</ElButton>
</el-form>
<el-alert
v-show="interviewScheduled"
title="INTERVIEW SCHEDULED!"
type="success">
</el-alert>
<el-form :model="ScheduleInterviewForm" :rules="rules" ref="ScheduleInterviewForm" :inline="true">
<el-form-item prop="schedule_datetime">
</el-form-item>
</el-form>
export default {
props: ['c', 'interview_types'],
data() {
return {
ResumeDialog: false,
ScheduleInterviewForm: {
schedule_datetime: null,
interview_type_id: null,
},
rules: {
schedule_datetime: [
{ type: 'date', required: true, message: 'Select Schedule time', trigger: 'blur' },
{ validator: isDateFuture, trigger: 'blur' },
],
interview_type_id: [
{ type: 'number', required: true, message: 'Select Interview type', trigger: 'blur' }
],
},
interviewScheduled: null,
}
},
methods: {
ScheduleInterview(form, hrcId) {
var that = this;
this.$refs[form].validate((valid) => {
if (valid) {
// AJAX: Create HrRequest
axios.post('/ajax/schedule_interview', {
interviewTypeId: this.ScheduleInterviewForm.interview_type_id,
scheduleDatetime: this.ScheduleInterviewForm.schedule_datetime,
hrcId
})
.then(function(res) {
that.interviewScheduled = true;
setTimeout(() => that.interviewScheduled = false, 3000);
console.log(res);
// that.candidates = res.data.candidates;
})
.catch(function(err) {
console.log(err);
});
} else {
return false;
}
});
},
},
components: { ElButton, ElDialog, ElCard },
}
here is my js page:
const app = new Vue({
el: '#app',
data: () => ({
hr_request: window.data.hr_request,
candidates: window.data.candidates,
interview_types: window.data.interview_types,
}),
methods: {
ScheduleInterview(requestCandidateId, interviewTime) {
console.log(requestCandidateId, interviewTime);
},
},
components: {
Candidate,
Schedule,
}
});
Please can any one help me..
Thanks in advance..
Since you want the inputed values in the form show up af
ter the form is successfully submitted
Add a property in your data property as below:
data(){
return{
showFormValues = false;
}
}
Add a div with the inputed values in paragraph tags below the form and show the div only if form is sucessfully sunbmitted usimg v-show as below:
<div v-show="showFormValues">
<p>date: {{ScheduleInterviewForm.schedule_datetime}}</p>
<p>type: {{ScheduleInterviewForm.interview_type_id}}</p>
</div>
Now in the success part then block of your form submittion click method set the value of showFormValues = true like this:
ScheduleInterview(form, hrcId) {
var that = this;
this.$refs[form].validate((valid) => {
if (valid) {
// AJAX: Create HrRequest
axios.post('/ajax/schedule_interview', {
interviewTypeId: this.ScheduleInterviewForm.interview_type_id,
scheduleDatetime: this.ScheduleInterviewForm.schedule_datetime,
hrcId
})
.then(function(res) {
that.interviewScheduled = true;
//show the input form values on succesful form submission
that.showFormValues = true;
setTimeout(() => that.interviewScheduled = false, 3000);
console.log(res);
// that.candidates = res.data.candidates;
})
.catch(function(err) {
console.log(err);
});
} else {
return false;
}
});
},