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

VueDemi: Developing Vue 2/3 Universal Libraries

We recently implemented VueDemi Vue 2/3 通用库开发, and accumulated quite a bit of experience. Here's a summary for reference, hoping it helps those doing similar work.

Core Concepts

Let's start with the basic implementation:

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

This code demonstrates the basic usage. In real projects, you also need to consider error handling and edge cases.

In-Depth Analysis

Building on this foundation, we can further optimize:

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

This pattern is very practical in large projects and can significantly reduce maintenance costs.

Implementation Experience

Usage in real projects tends to be more complex:

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

Through this approach, both the testability and scalability of the code are improved.

Optimization Strategies

Here is a complete example:

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

Pay attention to boundary condition handling, which is critical in production.

Summary

  • Code examples are for reference only and need to be adjusted according to your business scenario
  • VueDemi Vue 2/3 通用库开发 is not a silver bullet; choose based on your project scale and tech stack
  • Understanding underlying principles is more important than memorizing APIs

MIT Licensed