0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Nuxt.jsでフォームをComponent化した話

Last updated at Posted at 2021-10-28

初めてNuxt.jsを触って、ちょっとハマったところを備忘録的にメモしておきます。

環境

Nuxt.js 2.15.8
Vuetify 2.5.5

やりたいこと

新規登録と編集など、内容がかぶっているフォームがあり、まるッとコンポーネントにしたかった。

ESLintに引っかかったソースコード

parent.vue
<edit-form :form="form" />

edit-formから抜粋

form.vue
<v-text-field
    v-model="form.name"
    :counter="30"
    label="氏名"
/>

挙動は思った通りに動いていると思ったのですが、このv-modelがダメらしいんですね。

 Unexpected mutation of "form" prop

というエラーが出ました。

フォームプロップの予期せぬ突然変異とは…?

フロントをほとんどやったことがなかったのでお作法を知らなかったのですが、
コンポーネントで勝手に変えて親に知らせないのはダメ、っていうことみたい?

修正後

そこで、↓のように修正しました。

form.vue
<v-form @submit.prevent="$emit('send')">
// 中略
    <v-text-field
        :value="name"
        :counter="30"
        label="氏名"
        @input="$emit('update:name', $event)"
    />
// 中略
    <v-btn
        type="submit"
        color="primary"
        class="my-2"
        @click="$emit('submit')"
    >
        登録
    </v-btn>
</v-form>

<script>
export default {
    props: {
        name: { type: String, default: '' },
        // 中略
        // フォームの項目ごとに必要
    }
}
</script>
parent.vue
<edit-form v-bind.sync="form" @submit="submit"/>

余談

@input="$emit('update:name', $event.target.value)"としたら↓のエラーになってしまった。
どうやら$eventだけで良いっぽい。

TypeError: Cannot read property ‘value’ of undefined
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?