LoginSignup
6
4

More than 1 year has passed since last update.

CompositionAPIに対応したライブラリ「VueUse」を使ってみる

Posted at

Vue関連の便利なプラグインは数多ありますが、Vue.js3を学習しているときにCompositionAPIに対応したライブラリを見つけたので試してみました。

VueUseとは

VueUseはCompositionAPIに対応したさまざまな関数を用意しているライブラリです。
アニメーションやステート管理など便利な機能を簡単に実装することができます。
CompositionAPIのライブラリですがVue2でも使うことができます。

さっそく使ってみる

環境
npm : 7.15.1
node: v14.16.1
vue: 3.2.24
VueUse: 7.2.2

インストール

npm

npm i @vueuse/core

CDN

<script src="https://unpkg.com/@vueuse/shared"></script>
<script src="https://unpkg.com/@vueuse/core"></script>

今回はnpm を使ってインストールしましたがCDNで手軽に使うこともできます。
インストールが完了したら使いたい関数をimport {〇〇} from '@vueuse/core'でインポートすれば使えるようになります。

useMouseで座標を取得する

App.vue
<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <div style='text-align: center'>
    <UseMouse>
      x: {{ x }}
      y: {{ y }}
    </UseMouse>
  </div>

</template>

<script>
import { useMouse } from '@vueuse/core'

export default {
  name:'App',
  setup() {
    const { x, y, source } = useMouse()
    return { x, y, source}
  }  
}
</script>

1行の記述だけでマウスの座標を取得できました。

ezgif.com-gif-maker.gif

syncRefでソースとターゲットを同期させる

HelloWorld.vue
<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <div>
    <input v-model="source" placeholder="Source" type="text">
    <input v-model="target" placeholder="Target" type="text">
  </div>
</template>

<script>
import { ref } from 'vue' 
import { syncRef } from '@vueuse/core'

export default {
  name:'App',
  setup() {
    const source = ref('')
    const target = ref('')

    const stop = syncRef(source, target)

    source.value = 'hogehoge'
    console.log(target.value)

    return { source, target }
  }  
}
</script>

ターゲットのrefsをソースのrefsと同期させているのでソースの文字列を変えるとターゲットの文字列も変わりますが逆の場合は変わりません。
ezgif.com-gif-maker (1).gif

useElementSizeで要素のサイズを取得する

App.vue
<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld>
    Width: {{ width }}
    Height: {{ height }}
  </HelloWorld>
</template>
HelloWorld.vue
<template>
  <div ref="el">
    Height: {{ height }}
    Width: {{ width }}
  </div>
</template>

<script>
import { ref } from 'vue'
import { useElementSize } from '@vueuse/core'

export default {
  setup() {
    const el = ref(null)
    const { width, height } = useElementSize(el)

    return {
      el,
      width,
      height,
    }
  }
}
</script>

HTML要素のサイズをリアクティブに取得してくれます。

ezgif.com-gif-maker (2).gif

おわりに

VueUseは1行記述するだけで実装できてしまう機能も多く本当にお手軽に使えるライブラリだと思いました。CompositionAPIに基づくライブラリなのでまだリリースされてから日が浅いですが公式ドキュメントが充実していてデモを触ってみることもできるので見ているだけでも面白いです。
先日v.7.3.0がリリースされuseElementByPointなど新しい関数が追加され、使える機能が日に日に増えているのでこれからも追って見ていこうと思います!

6
4
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
6
4