Reputation: 519
I'm trying to select current element in Vuejs, here's my code:
<vs-input label="Password"
v-model="password"
danger-text="Wrong password"
:danger="this.classList.contains('invalid')"/>
But this
is not referring to the current element in Vuejs.
In JavaScript, this
referred to current element, but things are different here.
I'm wondering how to solve this problem.
Upvotes: 1
Views: 5851
Reputation: 46602
There is a cleaner way then using ref's to lookup if the plugin added a class.
Instead of having a top-level model for every form input username
, password
etc make a form
model which contains errors
and values
which encapsulate that form.
Then upon validation, set this.form.errors[theField]
with the error, then that error will be applied to :danger-text
and :danger="form.errors.password"
.
It will also make the error handling from serverside much easier as you simply plop errors back into the model.
For example:
data: () => ({
form: {
errors: {},
values: {
username:'',
password: ''
}
}
}),
methods: {
submit() {
this.form.errors = {}
if (!this.form.values.password) {
this.form.errors.password = 'Password is a required field.'
} else if (...) {
...
}
if (Object.keys(this.form.errors).length) return
// some ajax call
ajax.post(..).then((res) => {
if (res.errors) {
this.form.errors = res.errors
} else {
}
}).catch(e => {
// maybe set global alert
})
}
<vs-input label="Password"
v-model="form.values.password"
:danger-text="form.errors.password"
:danger="form.errors.password" />
Upvotes: 1
Reputation: 1
Add a ref
to that input then use $refs.input.$el.classList
:
<vs-input label="Password"
v-model="password"
danger-text="Wrong password"
ref="input"
:danger="$refs.input.$el.classList.contains('invalid')"
/>
Upvotes: 2