Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Vue コンポーネント実装パターン

seya
May 22, 2018

Vue コンポーネント実装パターン

v-meetup vol.7 でのLT資料です。

seya

May 22, 2018
Tweet

More Decks by seya

Other Decks in Programming

Transcript

  1. Ͱ΋ಠࣗͰఆٛͨ͠ίϯϙʔωϯτʹ v-model ࢖͍͍ͨ৔߹͸Ͳ͏͢Ε͹͍͍Ͱ͠ΐ͏ʁ <form> <toggle-button v-model="toggled" /> </form> ←͜Ε࡞Γ͍ͨ <template>

    <span class="toggle" role="checkbox" tabindex=“0" aria-checked="false" ></span> </template> ↓͜Μͳײ͡Ͱॻ͍ͯ ↓ ͜Μͳײ͡ʹ v-model ࢖͍͍ͨɻΠϕϯτϋϯυϥ౉ͯ͠͝ʹΐ͝ʹΐͱ͔ͨ͘͠ͳ͍ɻ
  2. v-model ͸ :value ͱ @input ͷ ૊Έ߹ΘͤͰͰ͖͍ͯΔ <input type="text" v-model="text"

    /> <input type="text" :value="text" @input="$emit('input', $event.target.value)" /> ྫ͑͹ ͸ ͱಉ͡
  3. ͳͷͰࢠڙͷํͰ͸͜Μͳײ͡Ͱॻ͍ͯ͋͛ͯ <template> <span class="toggle" role="checkbox" tabindex="0" @click="toggle" :aria-checked="value.toString()" ></span> </template>

    <script> export default { props: ['value'], methods: { toggle() { this.$emit('input', !this.value); } } }; </script>
  4. ͪͳΈʹ value ͱ ˏinput ͷͱ͜ʹͪΌΜͱ໊લ ͚͍ͭͨ৔߹͸ model ϓϩύςΟΛ࢖͑͹ՄೳͰ͢ <script> export

    default { model: { prop: 'toggled', event: ‘toggle' }, props: [‘toggled'], methods: { toggle() { this.$emit('toggle', !this.toggled); } } }; </script>
  5. $listeners ͰΠϕϯτϦεφʔΛऔಘͰ͖ΔͷͰɺͦΕΛ಺෦ ͷ input ʹ౉ͯ͋͛͠Δɻ <template> <label> {{ label }}

    <input :value="value" v-on="listeners" /> </label> </template> <script> computed: { listeners() { return { ...this.$listeners, input: event => this.$emit('input', event.target.value) } } } </script>
  6. inheritAttrs Λ false ʹͯ͠ v-bind ʹ $attrs Λ౉ͤ͹OK <template> <label>

    {{ label }} <input :value="value" v-on="listeners" v-bind="$attrs" /> </label> </template> <script> export default { inheritAttrs: false, // ଞͷ΍ͭ } </script>