Skip to content
⚠️ This article was written in 2022. Some content may be outdated.

VueDemi:Vue 2/3 ユニバーサルライブラリの開発

最近チームでVueDemi Vue 2/3 通用库开发,において多くの経験を積みました。参考のためにまとめましたので、同様の作業をされる方のお役に立てれば幸いです。

コアコンセプト

まず基本的な実装方法から見てみましょう:

javascript
import { ref, computed, watch, onMounted } from 'vue'

export default {
  setup() {
    const count = ref(0)
    const doubled = computed(() => count.value * 2)

    watch(count, (newVal, oldVal) => {
      console.log(`count: ${oldVal} -> ${newVal}`)
    })

    onMounted(() => { console.log('组件已挂载') })

    return { count, doubled }
  }
}

このコードは基本的な使用方法を示しています。実際のプロジェクトでは、エラー処理とエッジケースも考慮する必要があります。

詳細分析

この基盤の上で、さらに最適化できます:

javascript
import { reactive, toRefs, computed } from 'vue'

function useCounter(initial = 0) {
  const state = reactive({ count: initial, history: [initial] })
  const doubled = computed(() => state.count * 2)

  function increment() {
    state.count++
    state.history.push(state.count)
  }

  return { ...toRefs(state), doubled, increment }
}

このパターンは大規模プロジェクトで非常に実用的で、メンテナンスコストを大幅に削減できます。

実装経験

実際のプロジェクトでの使い方はより複雑になります:

javascript
import { ref, computed, watch, onMounted } from 'vue'

export default {
  setup() {
    const count = ref(0)
    const doubled = computed(() => count.value * 2)

    watch(count, (newVal, oldVal) => {
      console.log(`count: ${oldVal} -> ${newVal}`)
    })

    onMounted(() => { console.log('组件已挂载') })

    return { count, doubled }
  }
}

このアプローチにより、コードのテスト可能性とスケーラビリティの両方が向上します。

最適化戦略

以下は完全な例です:

javascript
import { reactive, toRefs, computed } from 'vue'

function useCounter(initial = 0) {
  const state = reactive({ count: initial, history: [initial] })
  const doubled = computed(() => state.count * 2)

  function increment() {
    state.count++
    state.history.push(state.count)
  }

  return { ...toRefs(state), doubled, increment }
}

境界条件の処理に注意してください。これは本番環境において非常に重要です。

まとめ

  • コード例は参考のみであり、ビジネスシナリオに応じて調整が必要です
  • VueDemi Vue 2/3 通用库开发は銀の弾丸ではなく、プロジェクトの規模と技術スタックに応じて選択する必要があります
  • APIを暗記するよりも、基盤となる原理を理解する方が重要です

MIT Licensed