"Experience the power of Vuejs 3 with Composition API: see the incredible render capabilities of v-model with

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.

Answer №1

When using {{ count }}, it is automatically unwrapped, while in v-model it is treated as v-model="{value:0}". To fix this, you can destructure 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn about ng-show in AngularJS

Is there a way to hide this tag if it doesn't have a subcategory? I tried using the condition item.length != 0 but it doesn't seem to be working properly. <multi-select-tree class="multiselectStyle groupStyle" data-input-model="ca ...

Using buttons as spinners for input elements with identical styles but unique identifiers

Currently, I am in the process of developing a project that involves users. In order to display all users, I am executing a query on an SQL database. After styling the interface, I have added an input element beside each user, which initializes at zero. Ad ...

Angular 7+: Trouble with displaying images from assets directory

Details regarding my Angular version: Angular CLI: 7.3.9 Node: 10.15.3 OS: win32 x64 Angular: 7.2.15 ... animations, common, compiler, compiler-cli, core, forms ... language-service, platform-browser, platform-browser-dynamic ... rout ...

Enhancing Promises.all with extra parameters

Looking to dive into promises, eager to learn. Here is an array of shopIds I'm working with: let shopIdsArray = ['shop1','shop2','shop3']; Additionally, there's an external promise call: getProducts(shopId, ' ...

Choosing an ID along with a numerical value in jQuery

Being new to both stackoverflow and jQuery, I'm facing a challenge in creating a basic function. In my website, there are multiple links with IDs such as "filtro1", "filtro2", and so on. My goal is to write a single piece of code that will be trigger ...

Revamp the props structure in Vue3 while preserving reactivity

When working with a component that retrieves API data and passes it down to child components, I encountered an issue. I attempted to split the information into separate ref objects for each child component but ran into a problem - reactivity was lost. The ...

A step-by-step guide on integrating drag and drop functionality for HTML elements using VueJs

Can anyone provide guidance on how to integrate drag and drop functionality, similar to JQuery, with vuejs? Specifically, I am interested in learning how to move elements within the DOM without using a plugin. Any insights or advice would be greatly apprec ...

To link circles vertically with a line and fill them with color when clicked, follow these steps:

I am looking to create a design similar to the image below using unordered list items. When a user clicks on a list item, I want the circle to fill with color. I have structured it by creating a div with nested list items and span elements. If a user click ...

Can a background image flow into another div?

My goal is to use this specific image as the background image for this particular page. I want the background image to begin within the navbar navbar-default class. However, I'm facing an issue. I need the image to extend into the next div, which is d ...

Assist me with Twitter

Seeking assistance with a coding issue related to displaying Twitter posts on a website. I have found a code snippet that accomplishes this: //Scrolling of tweets in the footer $(function () { var tweetVP = $("#footerTweetsViewport"); arrTweetNav ...

Having trouble accessing a PDF file using gview

Having trouble opening a document I am unable to preview the documents and I'm not sure what I'm missing. I have read through various StackOverflow questions and answers related to this issue, but still no luck. url = http://192.168.0.6:8077/ ...

What's the best way to add a Grid to a TabPanel in React without triggering any pesky warnings?

I have a question that should be clear from the context. I'm currently working with Tabs from Material-UI to display different Grids based on the user's selection. Each panel is supposed to contain a Grid with various text fields and components. ...

Experiencing difficulties applying a condition in a mongoDB projection

Imagine a scenario where I have a separate collection named 'Collection1' containing the following data: userID: "1" container:[ {"item" : "false", "price" : NumberDecimal("80"), "sizes" : "S", "arrayIndex" : NumberLong(0) } {"item" : ...

Repetitive occurrences of events being emitted from a VueJS component

As my mouse cursor hovers over and exits my VueJS component, specific methods are triggered accordingly. The methods that execute when the cursor enters and leaves my component: // Included in the "methods" section of my Vue component file onMouseEnter( ...

Using node.js, transform a multi-dimensional array into JSON

After combining a few simple arrays, I now have a large multidimensional array that I need to convert into a JSON string before sending it to Mongodb. Below is the structure of the array: [ '0', [ [ 'id', 1 ], [ &apos ...

jquery autocomplete utilizing an external json data feed

I am facing an issue with my autocomplete function that was initially working with a local json source. I have decided to move it to an external json file, as my current code is lengthy (16k lines). However, I am struggling to make it work with the externa ...

CSS margin-left causing issues in Chrome Extension

My current situation is incredibly puzzling, as I am at a loss for what is happening. I developed a Firefox add-on using jQuery and CSS to revamp a website. When attempting to transfer the add-on to Chrome (which was relatively straightforward due to the s ...

What is the best approach for creating a single jQuery click function to manage multiple elements within a slider?

Here's my query: I have a slider on my website where each slider item consists of an image and a Bandcamp iframe link. Below is an example code of one of the slider items: <div class="tapecol col-md-4"> <img class="media-ob ...

Modifying an element's value according to user input: Step-by-step guide

Within my dropdown menu, there is a single option labeled "Others". Upon selecting this option, a textbox appears allowing me to input custom text. Is it possible to dynamically update the value of the <option value="Others">Others</option>, ...

Guidelines for integrating Bootstrap-Vue into an ASP.net project within VisualStudio 2017

While we have a NuGet package available for Vue 2.5 to easily set things up in an ASP.net project in Visual Studio 2017, unfortunately, there is currently no Bootstrap-vue NuGet package. The Bootstrap-vue website provides instructions only for NPM and YAR ...