8
9

More than 3 years have passed since last update.

Vue.jsをTypeScriptで使う(Vuetify編)

Last updated at Posted at 2020-05-04

自分用忘備録
逐次追加します

環境

  • Vue 2.6.11
  • Vuetify 2.2.11
  • TypeScript 3.8.3

インストール時

エラー Property 'hello' does not exist on type 'Vue | Element | Vue[] | Element[]'.

型定義をtsconfig.jsonに追加する。

    "types": [
      "webpack-env",
      "vuetify"
    ],

Validation(Vuetify標準)

v-formのバリデーション関連関数

<v-form ref="form">とすると以下の関数が使える。

  • this.$refs.form.validate()
  • this.$refs.form.reset()
  • this.$refs.form.resetValidation()

部分的なバリデーションを行いたい場合はv-formを分けて別名のrefをつけてやればいい。

$refsの型には未定義なので、

パターン1 $refsany型のアクセサを作る(もしくは毎回as any)

get refs(): any {
  // eslint-disable-next-line
  return this.$refs;
}

hoge() {
  this.refs.form.validate();
}

パターン2 interfaceを作ってform用のアクセサを作る

export interface VForm {
  validate: () => boolean;
  reset: () => void;
  resetValidation: () => void;
}

get form(): VForm {
  // eslint-disable-next-line
  return (this.$refs as any).form;
}

hoge() {
  this.form.validate();
}

複数項目の相関チェック

getter (jsだとcomputed相当)で書く。

<v-text-field
  type="password"
  v-model="new_password"
  :counter="20"
  :rules="[rules.required]"
  label="パスワード"
  maxlength="20"
  required
/>
<v-text-field
  type="password"
  v-model="new_password_confirmation"
  :counter="20"
  :rules="[newPasswordConfirmationRule]"
  label="パスワード(再入力)"
  maxlength="20"
  required
/>
@Component
export default class Hoge extends Vue {
//...
  new_password = "";
  new_password_confirmation = "";

  get newPasswordConfirmationRule() {
    return this.new_password == this.new_password_confirmation || "同じパスワードを入力してください"
  }
//***
}
8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9