vee validate on custom select2 component not works - vuejs2

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'"

Related

Default props value are not selected in vue3 options api

I created a select2 wrapper in vue3 with options API everything working fine but the problem is that when getting values from calling API it's not selected the default value in the select2 option. but when I created a static array of objects it does. I don't know why it's working when it comes from the API
Parent Component
Here you can I passed the static options array in options props and my selected value is 2 and it's selected in my Select2 component, but when passed formattedCompanies it's not which is the same format as the static options array then why is not selected any reason here..?
<template>
<Form #submitted="store()" :processing="submitting">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>Company Name</label>
<Select2
:options="options"
v-model="selected"
placeholder="Select Company"
/>
<ValidationError :errors="errors" error-key="name" />
</div>
</div>
</div>
</Form>
</template>
<script>
import Form from "#/components/Common/Form";
import Select2 from "#/components/Common/Select2";
export default {
components: {
Select2,
Form
},
data() {
return {
selected : 2,
companies : [],
options: [ // static array
{ id: 1, text: 'hello' },
{ id: 2, text: 'hello2' },
{ id: 3, text: 'hello3' },
{ id: 4, text: 'hello4' },
{ id: 5, text: 'hello5' },
],
}
},
mounted() {
this.getAllMedicineCompanies()
},
computed:{
formattedCompanies() {
let arr = [];
this.companies.forEach(item => {
arr.push({id: item.id, text: item.name})
});
return arr;
}
},
methods: {
getAllMedicineCompanies(){
axios.get('/api/get-data?provider=companies')
.then(({ data }) => {
this.companies = data
})
},
}
}
</script>
Select2 Component
Here is what my select2 component look like, did I do anything wrong here, please anybody help me
<template>
<select class="form-control">
<slot/>
</select>
</template>
<script>
export default {
name: "Select2",
props: {
options: {
type: [Array, Object],
required: true
},
modelValue: [String, Number],
placeholder: {
type: String,
default: "Search"
},
allowClear: {
type: Boolean,
default: true
},
},
mounted() {
const vm = this;
$(this.$el)
.select2({ // init select2
data: this.options,
placeholder: this.placeholder,
allowClear: this.allowClear
})
.val(this.modelValue)
.trigger("change")
.on("change", function () { // emit event on change.
vm.$emit("update:modelValue", this.value);
});
},
watch: {
modelValue(value) { // update value
$(this.$el)
.val(value)
.trigger("change");
},
options(options) { // update options
$(this.$el)
.empty()
.select2({data: options});
},
},
destroyed() {
$(this.$el)
.off()
.select2("destroy");
}
}
</script>
Probably when this Select2 mounted there is no companies. It is empty array after that it will make API call and it it populates options field and clear all options.
Make:
companies : null,
Change it to
<Select2
v-if="formattedCompanies"
:options="formattedCompanies"
v-model="selected"
placeholder="Select Company"
/>
It should be like this:
<template>
<Form #submitted="store()" :processing="submitting">
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>Company Name</label>
<Select2
v-if="formattedCompanies"
:options="formattedCompanies"
v-model="selected"
placeholder="Select Company"
/>
<ValidationError :errors="errors" error-key="name" />
</div>
</div>
</div>
</Form>
</template>
<script>
import Form from "#/components/Common/Form";
import Select2 from "#/components/Common/Select2";
export default {
components: {
Select2,
Form
},
data() {
return {
selected : 2,
companies : null,
options: [ // static array
{ id: 1, text: 'hello' },
{ id: 2, text: 'hello2' },
{ id: 3, text: 'hello3' },
{ id: 4, text: 'hello4' },
{ id: 5, text: 'hello5' },
],
}
},
mounted() {
this.getAllMedicineCompanies()
},
computed:{
formattedCompanies() {
let arr = [];
this.companies.forEach(item => {
arr.push({id: item.id, text: item.name})
});
return arr;
}
},
methods: {
getAllMedicineCompanies(){
axios.get('/api/get-data?provider=companies')
.then(({ data }) => {
this.companies = data
})
},
}
}
</script>
The problem was that my parent component and Select2 component mounted at the same time that's why my computed value is not initialized so the selected value is not selected in the option,
problem solved by setTimeOut function in mounted like this
Select2 Component
<script>
mounted() {
const vm = this;
setTimeout(() => {
$(this.$el)
.select2({ // init select2
data: this.options,
placeholder: this.placeholder,
allowClear: this.allowClear
})
.val(this.modelValue)
.trigger("change")
.on("change", function () { // emit event on change.
vm.$emit("update:modelValue", this.value);
});
}, 500)
},
</script>

Handle interaction between vue fields

I have prepared a functional code example in JSFiddle of VUE field interaction.
https://jsfiddle.net/JLLMNCHR/2a9ex5zu/6/
I have a custom autocomplete component that works properly, a normal input field, and a 'Load' button which objetive is to load the value entered in the normal input in the autocomplete field.
This 'load' button is not working.
HTML:
<div id="app">
<p>Selected: {{test1}}</p>
<br>
<div>
<label>Test1:</label>
<keep-alive>
<autocomplete v-model="test1" v-bind:key="1" :items="theItems">
</autocomplete>
</keep-alive>
</div>
<br>
<label>Display this in 'test1':</label>
<input type="text" v-model=anotherField>
<button type="button" v-on:click="loadField()">Load</button>
<br>
<br>
<button type="button" v-on:click="displayVals()">Display vals</button>
</div>
<script type="text/x-template" id="autocomplete">
<div class="autocomplete">
<input type="text" #input="onChange" v-model="search"
#keyup.down="onArrowDown" #keyup.up="onArrowUp" #keyup.enter="onEnter" />
<ul id="autocomplete-results" v-show="isOpen" class="autocomplete-results">
<li class="loading" v-if="isLoading">
Loading results...
</li>
<li v-else v-for="(result, i) in results" :key="i" #click="setResult(result)"
class="autocomplete-result" :class="{'is-active':i === arrowCounter}">
{{ result }}
</li>
</ul>
</div>
</script>
VUE.JS:
const Autocomplete = {
name: "autocomplete",
template: "#autocomplete",
props: {
items: {
type: Array,
required: false,
default: () => []
},
isAsync: {
type: Boolean,
required: false,
default: false
}
},
data() {
return {
isOpen: false,
results: [],
search: "",
isLoading: false,
arrowCounter: 0
};
},
methods: {
onChange() {
// Let's warn the parent that a change was made
this.$emit("input", this.search);
// Is the data given by an outside ajax request?
if (this.isAsync) {
this.isLoading = true;
} else {
// Let's search our flat array
this.filterResults();
this.isOpen = true;
}
},
filterResults() {
// first uncapitalize all the things
this.results = this.items.filter(item => {
return item.toLowerCase().indexOf(this.search.toLowerCase()) > -1;
});
},
setResult(result) {
this.search = result;
this.$emit("input", this.search);
this.isOpen = false;
},
onArrowDown(evt) {
if (this.arrowCounter < this.results.length) {
this.arrowCounter = this.arrowCounter + 1;
}
},
onArrowUp() {
if (this.arrowCounter > 0) {
this.arrowCounter = this.arrowCounter - 1;
}
},
onEnter() {
this.search = this.results[this.arrowCounter];
this.isOpen = false;
this.arrowCounter = -1;
},
handleClickOutside(evt) {
if (!this.$el.contains(evt.target)) {
this.isOpen = false;
this.arrowCounter = -1;
}
}
},
watch: {
items: function(val, oldValue) {
// actually compare them
if (val.length !== oldValue.length) {
this.results = val;
this.isLoading = false;
}
}
},
mounted() {
document.addEventListener("click", this.handleClickOutside);
},
destroyed() {
document.removeEventListener("click", this.handleClickOutside);
}
};
new Vue({
el: "#app",
name: "app",
components: {
autocomplete: Autocomplete
},
methods: {
displayVals() {
alert("test1=" + this.test1);
},
loadField() {
this.test1=this.anotherField;
}
},
data: {
test1: '',
anotherField: '',
theItems: [ 'Apple', 'Banana', 'Orange', 'Mango', 'Pear', 'Peach', 'Grape', 'Tangerine', 'Pineapple']
}
});
Any help will be appreciated.
See this new fiddle where it is fixed.
When you use v-model on a custom component you need to add a property named value and watch it for changes, so it can update the local property this.search.

How to apply individual error message in VueJs Element?

I have a form (http://element.eleme.io/#/en-US/component/form) in application, where I do server side validation. But I have not glu how to add error message for specific inputs.
Each el-form-item needs a prop attribute for the frontend validation to work. They also need a bound error attribute. I just made each the same as the field name for simplicity, like so:
<el-form-item label="Email" prop="email" :error="errors.email">
<el-input v-model="form.email" type="email"></el-input>
</el-form-item>
Then when the form is submitted I run my validator for the frontend rules (using Element's rules). Right after that I use axios to post to the server (Laravel). I loop through any errors, and update the value in the errors object. Whenever the form is submitted, I clear the errors (if you don't clear them, the errors will not show up on consecutive form submissions).
data() {
let passwordsMatch = (rule, value, callback) => {
if ( value != this.form.password )
return callback(new Error('Passwords do not match'));
return callback();
};
let form = {
first_name: '',
last_name: '',
email: '',
phone: '',
password: '',
password_confirmation: '',
};
// copy blank values, not reference
let errors = {...form};
let blankErrors = {...form};
return {
form,
errors,
blankErrors,
rules: {
first_name: [
{ required: true, message: 'First Name is required', trigger: 'blur' },
],
last_name: [
{ required: true, message: 'Last Name is required', trigger: 'blur' },
],
email: [
{ required: true, message: 'Email is required', trigger: 'blur' },
{ type: 'email', message: 'Must be an email', trigger: 'blur' },
],
phone: [
{ required: true, message: 'Cell Phone is required', trigger: 'blur' },
// TODO: finish phone validation
//{ type: 'number', message: 'Must be a phone number', trigger: 'blur' },
],
password: [
{ required: true, message: 'Password is required', trigger: 'blur' },
],
password_confirmation: [
{ required: true, message: 'Password is required', trigger: 'blur' },
{ validator: passwordsMatch, trigger: 'blur' },
],
},
}
},
methods: {
createAccount() {
this.clearErrors();
let passed = this.runValidator();
if (! passed) return;
axios.post(`/register`, this.form)
.then(response => {
EventBus.$emit('user-form-completed', this.form);
return;
})
.catch(error => {
const errors = error.response.data.errors;
for (let index in errors) {
let error = errors[index][0];
this.errors[index] = error;
}
});
},
clearErrors() {
this.errors = {...this.blankErrors};
},
runValidator() {
let passed = false;
this.$refs.form.validate((valid) => {
if (valid) passed = true;
});
return passed;
},
},
I am using Laravel and I usually do like this, My validation in Laravel controller
return Validator::make($data, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
My vue.js code in if error comes
if(error.response.status == 400){
let errors = error.response.data.errors;
for(let i in errors){
document.querySelector("div[for='"+i+"']").innerHTML = errors[i][0];
}
}else if(error.response.status == 401){
console.log(error.response);
let errors = error.response.data;
document.querySelector("div[for='password']").innerHTML = errors;
}
Complete vue component is
const Login = {
template: `
<div class="container">
<div class="row row-body">
<div class="col-12 col-md-6 offset-md-3">
<div class="row">
<div class="col-12 col-md-12 text-center">
<h1>Login</h1>
</div>
</div>
<div class="row">
<div class="col-12 col-md-12">
<form method="POST" action="">
<div class="row pt-3 pb-3">
<div class="col-12 col-md-10 offset-md-1 form-group">
<input class="form-control form-rounded" placeholder="Email*" v-model="email">
<div for="email" class="text-danger"></div>
</div>
</div>
<div class="row pb-3">
<div class="col-12 col-md-10 offset-md-1 form-group">
<input class="form-control" placeholder="Password*" v-model="password" type="password">
<div for="password" class="text-danger"></div>
</div>
</div>
<div class="row pt-3">
<div class="col-12 col-md-12 form-group text-center">
<button #click="login" class="btn as-btn-outline as-btn-dark mx-2 my-2 my-sm-0 big-btn" type="button">LOGIN</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
`,
data(){
return {
email: '',
password: ''
}
},
mounted(){
/**/
},
methods:{
login: function(){
var formdata = {};
formdata.email = this.email;
formdata.password = this.password;
axios
.post('http://far.test/api/login',formdata)
.then(response => {
console.log(response.data);
if(response.data.token !== undefined){
this.$parent.is_auth = true;
sessionStorage.setItem('asset_token', response.data.token);
router.push({ path: '/home' });
}
})
.catch(error => {
if(error.response.status == 400){
let errors = error.response.data.errors;
for(let i in errors){
document.querySelector("div[for='"+i+"']").innerHTML = errors[i][0];
}
}else if(error.response.status == 401){
console.log(error.response);
let errors = error.response.data;
document.querySelector("div[for='password']").innerHTML = errors;
}
})
.finally(() => console.log('finally')/*this.loading = false*/);
},
}
}
And related laravel controller methods are
public function validateAuditLogin($data){
return Validator::make($data, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
}
public function loginForAudit(Request $request){
$requestAll = $request->all();
$pwd = base64_decode($requestAll["password"]);
for($i=0;$i<4;$i++){
$pwd = base64_decode($pwd);
}
$requestAll['password'] = $pwd;
$validator = $this->validateAuditLogin($requestAll);
if($validator->fails()){
return response()->json(['errors'=>$validator->messages()],400);
}
if ($user = \Auth::attempt(['email' => $requestAll['email'], 'password' => $requestAll['password'] ])) {
$token = str_random(40);
User::where('id',\Auth::id())->update(['api_token'=>$token]);
return response()->json(['token'=>$token]);
}else{
return response()->json('Email or password is incorrect',401);
}
}
I figured out a Laravel solution based on Laracast project. The advantage of this approach is that the Error class is reusable.
In your component.vue,
Bind individual input error with errors.get('field') e.g :error="errors.get('email')"
Import Error class (see snippet below)
Add errors object to vue data
Make axios request and record response data
<template>
<el-form label-position="top"
label-width="100px"
:model="loginForm"
:rules="rules"
#submit.prevent="validateForm"
ref="loginForm"
status-icon validate-on-rule-change>
<el-form-item label="email" prop="email" :error="errors.get('email')">
<el-input v-model="loginForm.email" placeholder="Enter your email"></el-input>
</el-form-item>
<el-form-item label="password" prop="password" :error="errors.get('password')">
<el-input v-model="loginForm.password" placeholder="Enter your password"></el-input>
</el-form-item>
<!-- Note about get() method in :error="errors.get('password')" see errors js -->
</el-form>
</template>
<script>
import { Errors } from './../templates/errors.js';
export default {
// Data
data() {
return {
loginForm: {
email: '',
password: '',
},
// This is where we manage laravel errors
errors: new Errors(),
// Local validation disabled
rules: {
email: [
{ required: false, message: 'Please enter your email', trigger: 'blur' },
// required set to false to for the sake of testing with laravel
],
password: [
{ required: false, message: 'Please enter your password', trigger: 'blur' },
// required set to false to for the sake of testing with laravel
],
}
};
},
// Methods
methods: {
// Validate form data
submitForm(loginForm) {
// Clear Laravel errors before submitting form
this.errors.clear()
this.$refs[loginForm].validate((valid) => {
if (valid && ! this.errors.any()) {
console.log('Data is validated. Submitting' + this.loginForm);
this.login()
this.$refs[loginForm].validate()
} else {
console.log('Cannot submit, Invalid data');
return false;
}
});
},
// post data
login(){
axios.post('/login'.login, this.loginForm).then( response => {
// Data submitted successifully
})
.catch(error => {
// There was an error like
this.errors.record(error.response.data.errors)
// Note: see errors.js for record method
});
}
}
}
</script>
Then import errors.js (credit Laracast project)
export class Errors {
/**
* Create a new Errors instance.
*/
constructor() {
this.errors = {};
}
/**
* Determine if an errors exists for the given field.
*
* #param {string} field
*/
has(field) {
return this.errors.hasOwnProperty(field);
}
/**
* Determine if we have any errors.
*/
any() {
return Object.keys(this.errors).length > 0;
}
/**
* Retrieve the error message for a field.
*
* #param {string} field
*/
get(field) {
if (this.errors[field]) {
return this.errors[field][0];
}
}
/**
* Retrieve flash message if any
*
* #param {string} field
*/
getFlash(field) {
if (this.errors[field]) {
return this.errors[field];
}
}
/**
* Record the new errors.
*
* #param {object} errors
*/
record(errors) {
this.errors = errors;
}
/**
* Clear one or all error fields.
*
* #param {string|null} field
*/
clear(field) {
if (field) {
if (this.has(field)) {
delete this.errors[field];
}
return;
}
this.errors = {};
}
}
add a ref with any name and do the following:
In js do this
this.$refs.formData.errorBucket=[]
<v-text-field
ref="formData"
:rules="[rules.required, rules.max]">
</v-text-field>

Why is the computed property of this component not reactive:

I have an object like this:
myObject: {
items: [{
title: '140',
isActive: true,
}, {
title: '7',
isActive: false
}, {
title: '10',
isActive: false
}]
}
Which I'm using like this:
<my-component :items="myObject.items"></my-component>
This is how the component looks like:
<template>
<div class="i-panel panel-container d-flex"
<div
v-for="item in prefs.items"
class="panel-item"
#click="onClick(item)">
<!-- some content -->
</div>
</div>
</template>
<script>
export default {
name: 'IPanel',
props: {
items: {
type: Array,
default () {
return []
}
}
},
computed: {
// code
prefs () {
return {
items: this.items
}
}
},
methods: {
onClick (item) {
this.prefs.items.forEach(item => {
if (JSON.stringify(item) === JSON.stringify(clickedItem)) {
item.isActive = true
}
})
}
}
}
</script>
When I click an item (and that item is the same as the clickedItem), it's supposed to become isActive true. It does. But I have to refresh the Vue devtools or re-render the page for the change to take effect.
Why isn't item.isActive = true reactive?
In the code you posted, you are using a clickedItem object that is not defined anywhere. I don't know if this is just in the process of writing your question or if it is your problem.
However, when using clickedItem the right way, it seems to work: https://jsfiddle.net/d5z93ygy/4/
HTML
<div id="app" class="i-panel panel-container d-flex">
<div
v-for="item in prefs.items"
class="panel-item"
#click="onClick(item)">
<!-- some content -->{{ item.isActive ? 'active' : 'inactive' }}
</div>
</div>
JS
new Vue({
el: "#app",
data: {
items: [{
title: '140',
isActive: true,
}, {
title: '7',
isActive: false
}, {
title: '10',
isActive: false
}]
},
computed: {
// code
prefs () {
return {
items: this.items
}
}
},
methods: {
onClick (clickedItem) {
this.prefs.items.forEach(item => {
if (JSON.stringify(item) === JSON.stringify(clickedItem)) {
item.isActive = true
}
})
}
}
})
Change
<div
v-for="item in prefs.items"
class="panel-item"
#click="onClick(item)">
<!-- some content -->
</div>
to
<div
v-for="(item, index) in prefs.items"
class="panel-item"
#click="onClick(index)">
<!-- some content -->
</div>
Then, in your change method, go like this:
onClick (index) {
Vue.set(this.items, index, true);
}
https://v2.vuejs.org/v2/guide/list.html#Object-Change-Detection-Caveats

get the form values on the same page after submit the the form in vue.js

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;
}
});
},