
VueUseとは
Vue.jsの便利なComposition APIライブラリ。
VueUseを使用するとCounterなどVue.jsでよく使用されるものが簡単に作成できるようになる。
Vue 2で使用するには以下の手順でインストールしてmain.jsでVueCompositionApiをimportしてVue.useで適用する準備が必要。
vue create my-vueuse cd my-vueuse yarn add @vueuse/core@vue2 @vue/composition-api yarn serve
1 2 3 4 5 6 7 8 9 | import Vue from 'vue' import App from './App.vue' import VueCompositionApi from '@vue/composition-api' Vue.use(VueCompositionApi) new Vue({ render: h => h(App), }).$mount( '#app' ) |
useCounter
useCounterを使用するとCounterが使用できるようになる。
ライブラリを使用しないとこちらの例のようにコード量がそれなりに多くなってしまうが、useCounterを使用するとかなり少ないコード量で済む。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | < template > < div > < h1 >count: {{ count }}</ h1 > < button @ click = "inc()" >Increment</ button > < button @ click = "dec()" >Decrement</ button > < button @ click = "inc(5)" >Increment (+5)</ button > < button @ click = "dec(5)" >Decrement (-5)</ button > < button @ click = "set(100)" >Set (100)</ button > < button @ click = "reset()" >Reset</ button > </ div > </ template > < script > import { defineComponent } from '@vue/composition-api' import { useCounter } from '@vueuse/core' export default defineComponent({ setup() { const { count, inc, dec, set, reset } = useCounter() return { count, inc, dec, set, reset, } } }) </ script > |
useMouse
マウスポインタのxとyの座標を取得できる。
特定の要素内のxとyの座標を取得する場合はuseMouseInElementを使用する。
useBattery
Battery Status APIを簡単にできるようになるが、 Battery Status APIはDeprecated(非推奨)なので使用しないほうが良い。
…というか使用する機会がない。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | < template > < ul > < li >isCharging: {{ isCharging }}</ li > < li >chargingTime: {{ chargingTime }}</ li > < li >dischargingTime: {{ dischargingTime }}</ li > < li >level: {{ level }}</ li > < li >supported: {{ supported }}</ li > </ ul > </ template > < script > import { defineComponent } from '@vue/composition-api' import { useBattery } from '@vueuse/core' export default defineComponent({ setup() { const { isCharging, chargingTime, dischargingTime, level, supported } = useBattery() return { isCharging, chargingTime, dischargingTime, level, supported } } }) </ script > |
VueUseはuseBatteryのようにまともに使えないものがいくつかあるので注意が必要。
VueUseの公式ドキュメント
VueUseの公式ドキュメントはStorybookで作成されており、以下のURLにある。
https://vueuse.js.org/?path=/story/docs--read-me
jsではなくjsxで書かれていてTypeScriptのTypingなどもあるので、これらを知らないと理解しづらい。
JavaScriptだけで書いている場合はTyping部分は無視して、jsxは基本的な部分はjsと同じなのでVue.jsのJSXのドキュメントを読めば違いが理解できるだろう。