I am a newbie to vuetify.
To apply password validation, we defined as follows.
<v-text-field
class="text-body-2"
value="test"
v-model="password"
:append-icon="password_show ? 'mdi-eye' : 'mdi-eye-off'"
:rules="[password_rules.required, password_rules.min]"
:type="password_show ? 'text' : 'password'"
@click:append="password_show = !password_show"
outlined
clearable
background-color="#f7f7f7"
:label="$t('word.password')"
></v-text-field>
<script>
import { reactive, toRefs } from '@vue/composition-api';
import { getLoginToken } from '@/api/login';
export default {
setup() {
const state = reactive({
username: '',
password: '',
loginForm: null,
password_show: false,
username_rules: {
required: (value) => !!value || this.$t('word.require_username'),
min: (v) => v.length >= 8 || this.$t('word.login_rules1'),
},
password_rules: {
required: (value) => !!value || this.$t('word.require_password'),
min: (v) => v.length >= 8 || this.$t('word.login_rules1'),
},
});
const action = {
login: async () => {
console.log(
await getLoginToken({
username: state.username,
password: state.password,
}),
);
},
};
return { ...toRefs(state), action };
},
};
</script>
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??
data() {
return {
password_rules: {
required: (value) => !!value || this.$t('word.require_password'),
min: (value) => value.length >= 8 || this.$t('word.login_rules1'),
},
};
},
I want to define it all at once inside setup().
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:
setup() {
const state = reactive({
...
username_rules: {
// can't use "this" here
required: (value) => !!value || this.$t('word.require_username'),
// can't use "this" here
min: (v) => v.length >= 8 || this.$t('word.login_rules1'),
},
password_rules: {
// can't use "this" here
required: (value) => !!value || this.$t('word.require_password'),
// can't use "this" here
min: (v) => v.length >= 8 || this.$t('word.login_rules1'),
},
});
...
},
data() {
return {
password_rules: {
// "this" is available here because it's in `data`
required: (value) => !!value || this.$t('word.require_password'),
min: (value) => value.length >= 8 || this.$t('word.login_rules1'),
},
};
},
To access i18n in the setup function you need something like this:
const { t } = VueI18n.useI18n() // call `useI18n`, and spread `t` from `useI18n` returning
return { t } // return render context that included `t`
Here's more on using i18n with the Vue 3 composition api