DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Designing a Java Connector for Software Integrations
  • Vibe Coding With GitHub Copilot: Optimizing API Performance in Fintech Microservices
  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • Unlocking the Benefits of a Private API in AWS API Gateway

Trending

  • AWS to Azure Migration: A Cloudy Journey of Challenges and Triumphs
  • Agile and Quality Engineering: A Holistic Perspective
  • How Trustworthy Is Big Data?
  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  1. DZone
  2. Data Engineering
  3. Databases
  4. Vue 3 Reactivity Composition API Using Reactive() And Ref()

Vue 3 Reactivity Composition API Using Reactive() And Ref()

Learn how to use reactivity in Vue 3 with the Composition API approach by using reactive and ref functions.

By 
Saurabh Dashora user avatar
Saurabh Dashora
DZone Core CORE ·
May. 05, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
10.8K Views

Join the DZone community and get the full member experience.

Join For Free

Reactivity is a key pillar for building VueJS applications. While VueJS Reactivity using Options API is quite powerful, more and more developers are moving to Composition API for building their Vue applications. Thankfully, Vue 3 Reactivity with Composition API is equally robust.

Vue 3 Reactivity with Composition API is driven by reactive() and ref() functions. These functions turn the component model data reactive so that Vue is able to track changes. However, both reactive() and ref() have their specific use-cases. It is important to know which function should be used in which particular scenario.

Vue 3 Options API and Composition API has differing syntax for managing reactive variables but the concept of reactivity remains the same.

In this post, we will look at reactivity in Vue 3 Composition API for a Single File Component or SFC. 

Vue 3 reactive() Function

The reactive() function in VueJS helps create a piece of reactive state.

Vue.js Component
 
import { reactive} from 'vue'

// reactive state
const state = reactive({
  currentCounterStatus: '',
})

Vue is able to track mutations of any property within the reactive object. In the above example, if the value of currentCounterStatus changes, VueJS will automatically update the DOM.

We can use the reactive state variable within the template by using template syntax.

HTML
 
<template>
  <h2>{{ state.currentCounterStatus }}</h2>
</template>

The value of the reactive state can be updated as below:

JavaScript
 
function increment() {
  state.currentCounterStatus = 'Incremented'
}

We can trigger the increment() function using any click handler.

The reactive() API has some limitations as below:

  • We can use reactive() API to only declare objects, arrays, or other collection types such as Map or Set. Basically, reactive() function does not work for primitives such as string, integer, boolean, etc. In my view, this is a big disadvantage that limits the use of reactive() API.
  • We must always keep the same reference to the reactive object. In other words, if we update the value of a reactive object by again calling reactive() function, the reactivity connection to the first object is lost. See the below example:
JavaScript
 
import { reactive} from 'vue'

// reactive state
let state = reactive({
  currentCounterStatus: '',
})

state = reactive({
  currentCounterStatus: 'Incremented'
})

Vue 3 Reactivity Using ref() Function

Vue 3 also provides the ref() function to declare a reactive state. Basically, the ref() function solves the limitations of the reactive() function. Mainly, ref() can hold any type of value including primitives.

See the below example:

Vue.js Component
 
<template>
  <h1>{{ appName }}</h1>
  <h2>Count is: {{ counter }}</h2>
</template>

Basically, ref() takes the input argument and wraps it within an object. This object has a value property. In other words, for the above example, we can access the appName variable as appName.value. Also, the counter value can be accessed as counter.value.

Vue 3 Ref Unwrapping in Templates

We can also access reactive variables from ref() function within the template.

See the below example:

Vue.js Component
 
<template>
  <h1>{{ appName }}</h1>
  <h2>Count is: {{ counter }}</h2>
</template>

As you can see, here we don’t need to use counter.value or appName.value. Basically, when we access refs as top-level properties in the template, VueJS automatically unwraps them. Therefore, no need to use .value.

An important point is that ref unwrapping works only for top-level properties. It won’t work for an example as below:

JavaScript
 
const counterStatusObject = {
  status: ref(''),
}

This is because counterStatusObject.status is a Javascript object.

Vue 3 Ref Unwrapping in Reactive Objects

We can also add a ref variable as a property of a reactive object. See below:

JavaScript
 
const appName = ref('Counter Application')
const appObject = reactive({
   appName
})

console.log(appObject.appName)

In this case, we can directly access appName without the .value.

Vue 3 Reactivity Transform

You might feel that using .value is unnecessarily cumbersome. It reduces the simplicity of accessing variables in a template.

Vue 3 provides a compile-time transform that can get around this issue. We can now use $ref() to declare a reactive variable and directly access it without .value.

JavaScript
 
const appName = $ref('Counter Application')
const counter = $ref(0)

function increment() {
  counter++
}

However, do note that this is still an experimental feature and is prone to changes.

Conclusion

In this post, we covered Vue 3 Reactivity using Composition API. As part of this, we looked at the reactive() and ref() functions available with Vue that help us declare reactive objects and variables. 

If you have any comments or queries about this post, please feel free to mention them in the comments section.

API

Published at DZone with permission of Saurabh Dashora. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Designing a Java Connector for Software Integrations
  • Vibe Coding With GitHub Copilot: Optimizing API Performance in Fintech Microservices
  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • Unlocking the Benefits of a Private API in AWS API Gateway

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!