vuelidate
,但由于某些原因,当加载页面时,它会立即显示错误,但我只想在按下“下一步”按钮时显示错误。
<template>
<div>
<div class="question">
<div class="box-heading">
<h4> {{$t('ethnicity')}}</h4>
</div>
<div class="row justify-content-center">
<div class="col-md-6">
<div class="form-group">
<select class="form-control form-control-lg" tabindex="0" name="ethnicity" @change="selectEvent" :value="ethnicity">
<option value="" disabled selected>{{$t('ethnicityDefaultMessage')}}</option>
<option v-for="(value, key) in ethnicityData" :value="value.value">{{$t('ethnicity.' + value.value)}}</option>
</select>
<div class="alert alert-danger" role="alert" v-if="!$v.ethnicity.required">
{{$t('errorCheckRequired')}}
</div>
</div>
</div>
</div>
<div class="text-center">
<button class="btn btn-primary btn-block btn-lg mb-3 continue-btn" @click="validate">
{{$t('next')}}
<i class="fas fa-chevron-right"></i></button>
</div>
</div>
</div>
</template>
import { mapGetters, mapActions } from 'vuex';
import { validationMixin } from 'vuelidate';
import { required} from 'vuelidate/lib/validators';
export default {
mixins: [validationMixin],
components: {Loader},
validations: {
ethnicity: {
required,
},
},
computed: {
...mapGetters({
'ethnicity': 'getEthnicity',
'ethnicityData' : 'getEthnicityData'
})
},
methods: {
...mapActions(['updateData', 'goToNextStep']),
/**
* If all fields are valid move to the next step
*/
validate: function(){
this.$v.$touch();
if (!this.$v.$invalid) {
this.goToNextStep();
}
},
/**
* Update store when we selecting ehtnicity
*/
selectEvent: function(event){
this.updateProfileData({key: event.target.name, value: event.target.value});
},
}
商店看起来是这样的:
import * as types from '../mutation-types';
import {get, makeUrl, post, serialize} from '../../../../common/request';
import {PROFILE_DATA_SAVE_URL} from "../../api/urls";
const state = {
ethnicityData: [
{value: 'white'},
{value: 'black'},
{value: 'hispanic'},
{value: 'america_indian_or_alaska'},
{value: 'asian_indian'},
{value: 'chinese'},
{value: 'filipino'},
{value: 'japanese'},
{value: 'korean'},
{value: 'vietnamese'},
{value: 'pacific_islander'},
{value: 'middle_eastern'},
{value: 'other_asian'},
{value: 'other'},
{value: 'not_answer'}
],
currentStep: 0,
ethnicity: null,
};
const getters = {
getEthnicityData: state => state.ethnicityData
getEthnicity: state => state.ethnicity,
};
const actions = {
updateProfileData({commit}, profileData) {
commit(types.UPDATE_PROFILE_DATA, profileData);
},
goToNextStep({commit}) {
commit(types.NEXT_STEP);
},
};
const mutations = {
[types.UPDATE_PROFILE_DATA](state, data) {
state.ethnicity = data;
},
[types.NEXT_STEP](state, data) {
state.currentStep++;
},
};
我简化了一个代码,省略了除一个(种族)以外的所有数据,并从存储中删除了大部分逻辑(偶尔也会犯一些错,抱歉)。
所以问题是组件何时加载
this.$v.$invalid
,但我希望它是有效的,并且只想在单击“下一步”时运行验证。