Home > Net >  Vuejs 3 (Composition API) v-model render [object Object]
Vuejs 3 (Composition API) v-model render [object Object]

Time:08-17

I tried to create reusable/composable hooks in vuejs 3 called useCounter. The function return object count (ref) and increment. When I set v-model.number="counter.count" it will render [object Object], but for v-model.number="count" it render correctly

I increment counter.count from App.vue in increment() also works

App.vue

<script setup>
import { ref, computed, unref } from 'vue'
import useCount from './useCount.js'

const count = ref(5)

const counter = useCount({
  initialCount: 5
})

const increment = () => {
  count.value   // Added
  counter.count.value   // Added
}

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>

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

Result: Screenshot

CodePudding user response:

In {{ count }} is unwrapped automatically, and in v-model is treated as v-model="{value:0}", so you could fix it by destructing the returned value from the composable hook :

<script setup>
import { ref, computed, unref } from 'vue'
import useCount from './useCount.js'
const {count,increment} = useCount({
  initialCount: 5
})
</script>

<template>
  <h1>{{ count }}</h1>
  <input v-model.number="count" />
  <button @click="increment">
    Increment useCount
  </button>

</template>

DEMO

  • Related