In my exploration of Vue.js 3, I ventured into creating reusable and composable hooks which I named useCounter
. This function returns an object containing the count
(ref) and increment
. Interestingly, when I use
v-model.number="counter.count"
, it renders [object Object]. However, using v-model.number="count"
displays the correct output.
I also observed that incrementing counter.count
from within App.vue
by calling increment()
works flawlessly.
Here is a snippet from App.vue:
<script setup>
import { ref } from 'vue'
import useCount from './useCount.js'
const count = ref(5)
const counter = useCount({
initialCount: 5
})
const increment = () => {
count.value++
counter.count.value++
}
console.log("count", count)
console.log("counter.count", counter.count)
</script>
<template>
<h1>{{ counter.count }}</h1>
<input v-model.number="counter.count" />
<button @click="counter.increment">
Increment useCount
</button>
<h1>{{ count }}</h1>
<input v-model.number="count" />
<button @click="increment">
Increment all
</button>
</template>
For the implementation of useCounter.js
:
import { ref } from 'vue'
const useCount = (props = {}) => {
const count = ref(props.initialCount ?? 0)
const increment = () => {
count.value++
}
return {
increment,
count,
}
}
export default useCount
To view the result, you can check out the screenshot here.