I am a newbie to vuetify.
To apply password validation, we defined as follows.
JavaScript
x
15
15
1
<v-text-field
2
class="text-body-2"
3
value="test"
4
v-model="password"
5
:append-icon="password_show ? 'mdi-eye' : 'mdi-eye-off'"
6
:rules="[password_rules.required, password_rules.min]"
7
:type="password_show ? 'text' : 'password'"
8
@click:append="password_show = !password_show"
9
outlined
10
clearable
11
background-color="#f7f7f7"
12
:label="$t('word.password')"
13
></v-text-field>
14
15
JavaScript
1
37
37
1
<script>
2
import { reactive, toRefs } from '@vue/composition-api';
3
import { getLoginToken } from '@/api/login';
4
5
export default {
6
setup() {
7
const state = reactive({
8
username: '',
9
password: '',
10
loginForm: null,
11
password_show: false,
12
username_rules: {
13
required: (value) => !!value || this.$t('word.require_username'),
14
min: (v) => v.length >= 8 || this.$t('word.login_rules1'),
15
},
16
password_rules: {
17
required: (value) => !!value || this.$t('word.require_password'),
18
min: (v) => v.length >= 8 || this.$t('word.login_rules1'),
19
},
20
});
21
22
const action = {
23
login: async () => {
24
console.log(
25
await getLoginToken({
26
username: state.username,
27
password: state.password,
28
}),
29
);
30
},
31
};
32
33
return { toRefs(state), action };
34
},
35
};
36
</script>
37
When applied as follows, password_show works well, but rules do not apply.
However, as in the code shown as an example, if you subtract it with data() , it works well. What is the reason??
JavaScript
1
9
1
data() {
2
return {
3
password_rules: {
4
required: (value) => !!value || this.$t('word.require_password'),
5
min: (value) => value.length >= 8 || this.$t('word.login_rules1'),
6
},
7
};
8
},
9
I want to define it all at once inside setup().
Advertisement
Answer
In the vue setup function, unlike in data
, you don’t have access to this
, so this.$t
is undefined in your rules in the setup function:
JavaScript
1
19
19
1
setup() {
2
const state = reactive({
3
4
username_rules: {
5
// can't use "this" here
6
required: (value) => !!value || this.$t('word.require_username'),
7
// can't use "this" here
8
min: (v) => v.length >= 8 || this.$t('word.login_rules1'),
9
},
10
password_rules: {
11
// can't use "this" here
12
required: (value) => !!value || this.$t('word.require_password'),
13
// can't use "this" here
14
min: (v) => v.length >= 8 || this.$t('word.login_rules1'),
15
},
16
});
17
18
},
19
JavaScript
1
10
10
1
data() {
2
return {
3
password_rules: {
4
// "this" is available here because it's in `data`
5
required: (value) => !!value || this.$t('word.require_password'),
6
min: (value) => value.length >= 8 || this.$t('word.login_rules1'),
7
},
8
};
9
},
10
To access i18n in the setup function you need something like this:
JavaScript
1
3
1
const { t } = VueI18n.useI18n() // call `useI18n`, and spread `t` from `useI18n` returning
2
return { t } // return render context that included `t`
3
Here’s more on using i18n with the Vue 3 composition api