LoginSignup
1
1

More than 3 years have passed since last update.

(Vue.js) Component化 デモ(簡単なFormとボタンイベントの実装)

Last updated at Posted at 2019-07-11

目標: Vueのコンポーネント化を理解する。

Vue.js の Component の組み立て方を理解するための、シンプルなデモです。(Componentの組み立て方にフォーカスした簡単な実装なのでデザインは行っていません。)

0. ディレクトリ構成

 |-App.vue
 |-assets
 | |-logo.png
 |-components
 | |-Description.vue
 | |-FormSection.vue
 | |-MyLabel.vue
 | |-MyOption.vue
 | |-MyRadioGroup.vue
 | |-MyTextbox.vue
 | |-SubTitle.vue
 |-main.js

1. コンポーネント側の実装

propsのデータをtemplateに代入する。
(:name="xxx" は v-bind:name="xxx" の省略した記法で、="xxx" を 変数xxx の値を代入する、と解釈する。)

/components/MyOption.vue
<template>
  <p>
    <label :for="id" v-if=" text !== '' ">{{ text }}</label>
    <select :id="id">
      <option
        v-for="item in myoptions"
        :key="item.id"
        :value="item.id"
        :selected="item.id === selectedValue.id"
      >{{ item.name }}</option>
    </select>
  </p>
</template>


<script>
export default {
  props: {
    text: {
      type: String
    },
    id: {
      type: String,
      required: true
    },
    myoptions: {
      type: Array,
      required: true
    },
    selectedValue: {
      type: Object
    }
  },
};
</script>

2. 呼び出し側の実装

  • componentを import してexport defaultするObjectに加える。
  • template内で、component のDOM を呼び出し、その propsに対して、値を設定していく。
App.vue
<template>
  <div id="app">
    <h2>アンケート</h2>
    <p>アンケートにご協力ください</p>
    <form v-on:submit.prevent >
      <MyOption
        text="あなたの住んでいる都道府県は?"
        id="prefecture"
        :myoptions="[{id:1,name:'東京都'},{id:2,name:'それ以外'}]"
        :selectedValue="{id:1}"
      ></MyOption>
      <button @click="gatherResult">send</button>
    </form>
    <div v-if=" this.result.length !== 0 ">{{ result }}</div>
  </div>
</template>

<script>
import MyOption from "./components/MyOption.vue";

export default {
  name: "App",
  data: () => {
    return {
      result: []
    };
  },
  methods: {
    gatherResult() {
      this.result = [];
      this.result.push({
        prefecture: document.getElementById("prefecture").value
      });
    }
  },
  components: {
    MyOption,
  }
};
</script>

上のような形でselect、text、radioのコンポーネントを作成しました。実際のコードはこのような形で動きます。

enqeto.gif

ソースコード
https://w889n.codesandbox.io/
https://github.com/ttn1129/VueComponentMyOption

変更に強くなる

今回はデザインなしなのですが、デザインをVue componentで作って、使いまわしておけば、一つの変更をComponentを直せばすべてに反映することもできるため、保守性が高まります。(こちらの資料にデザインシステムの一つである、Atomicデザインでの開発について大変詳しく記載して頂いていました。
https://speakerdeck.com/nrslib/a-beginners-guide-to-atomic-design 

今後は typescript、jest に手を出していきたい。。
以上です。

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