LoginSignup
5
7

More than 3 years have passed since last update.

【Nuxt.js】フォームをコンポーネント化した時のメモ(子Componentで変更されたv-modelの値を親に反映する)

Posted at

概要

  • フォームの入力欄をコンポーネント化した時のメモ
  • 今回は例として、componentsに作成したtext_box.vueというファイルをpages配下のindex.vueに呼び出すことを想定したもの
  • text_box.vueにはラベルと入力欄をセットで登録

実際のコード

  • 入力値input_textexportする
components/TextBox.vue
<template>
  <div>
    <p>ラベル名</p>
    <input type="text" v-model="input_text" />
  </div>
</template>

<script>
export default {
  model: {
    prop: "input",  // 親側で"input"のbindをv-model`input_text`から行えるようになる
    event: "change"  // 変更というイベント
  },
  props: {
    input: String,  // input_textのデータ型を設定
  },
  // 子から親への変更を反映させるため算出プロパティを定義
  computed: {
    input_text: {
      // input_textの値を取得
      get() {
        return this.input  // ゲッターには戻り値が必要 modelプロパティで指定した"input"を戻り値とする
      },
      // input_textが変更されると以下が動作
      set(value) {
        this.$emit("change", value)  // modelプロパティのeventで指定されたイベント"change"を$emitする(親にデータを渡す)
      }
    }
  }
}
</script>
  • text_box.vueコンポーネントをimportしてinput_textを呼び出す
pages/index.vue
<template>
  <section>
    <div class="input_form">
      <InputText v-model="input_text" />
      <button @click="submit">送信</button>
    </div>
  </section>
</template>

<script>
import InputText from "~/components/TextBox.vue"

export default {
  components: {
    InputText
  },
  data() {
    return {
      input_text: null  // 初期値を設定
    }
  },
  methods: {
    submit() {
      axios
        .post(url, input_text)  // urlにはAPIのパスを指定 入力値`input_text`をPOST
        .then(res => {
          // 処理
        })
        .catch(e => {
          // 処理
        })
    }
  }
}
</script>

参照

5
7
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
5
7