0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

VueのComposition APIを覚えるのが辛いから独自ライブラリを作った

Last updated at Posted at 2025-02-03

VueのComposition API覚えるの辛い

なんでも、Vueのバージョンが上がると書き方までがらっと変わるんですよ。信じられません。
開発者がどういうつもりなのかわかりません。それでもうVueを使うのは愛想が尽きました。
でもSPAは作らないといけないので、独自のライブラリを作ることにしてそれを使ってます。

注:VueのOptions APIとComposition API

コメントで教えてもらいましたがVueにはOptionsとCompositionのAPIが2つあってどちらか選べるようです。私はComposition APIが新しいVueの書き方だと思っていたのですが、従来のOptions APIも使えます。これからのVueはOptionsとCompositionの両方のAPIをサポートし続けるのでしょうか?
AIに聞いた限りではOptions APIを廃止する予定はないとのことですが、そうなるとVueはOptionsとCompostionの両方をサポートし続けていくということになりそうです。
つまり私も独自ライブラリは作らずにOptions APIを使っていけばよかった、という話になります。でももう作っちゃったからね。

仮想DOMなんて知らん

独自ライブラリは仮想DOMには対応しておらず、ただのDOM操作をするだけのライブラリです。
えっ! それってjQueryじゃあかんの? と火の玉ストレートで突っ込まれるかもしれませんが、私が欲しかったのはVueのような使い勝手のあるDOM操作のライブラリです。

イベント駆動にした

最近イベント駆動に凝ってて、このライブラリにもイベント駆動を導入しました。
コンポーネント間の通信はイベントを使って行えるようにしています。

// ああ!コードを書かないといけない!
class NameList extends Component {
  constructor (hub) {
    super(hub, {
        name: 'NameList',
    })
  }

  receive (event) {
    switch (event.what) {
    case 'hello': console.log('hello'); break
    }
  }
}

じつは実装しておいてなんですがコンポーネント間の通信は込み入った処理を実装しないとあまり必要になりません。
たとえばコンポーネントAからコンポーネントBに再描画を依頼したい場合はイベントをディスパッチしてお願いします。

// ああ!またコードを書かないといけない!
class ComponentA extends Component {
    constructor (hub) {
        super(hub, {
            name: 'ComponentA',
            template: `<button>click me</button>`,
        })
        this.onclick('button', () => {
            // ボタンがクリックされたらコンポーネントBに再描画を依頼
            this.hub.emit(this.name, 'ComponentB', 'redraw')
        })
    }
}

class ComponentB extends Component {
    constructor (hub) {
        super(hub, {
            name: 'ComponentB',
            template: `<div>hello</div>`,
        })
    }

    receive (event) {
        switch (event.what) {
        case 'redraw':
            this.setText('div', 'HELLO')
            break
        }
    }
}

各コンポーネントには名前がついていて、その名前でイベントを受信します。これで違うコンポーネントでの再描画も楽ちんです。

Rootコンポーネントを作らないとダメ

Rootコンポーネントが必要です。これを定義して目的の要素に注入します。

class Root extends Component {
    constructor (hub) {
        super(hub, {
            name: 'Root',
            template: `<div>Root</div>`,
        })
    }
}

let root = new Root(new Hub())
// 要素にマウント。Vue的!
root.mount('#app')

おわりに

あああ!!!ハンバーグステーキが食べたい!!!

0
0
3

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?