In this tutorial, we will learn about using reactive()
and ref()
in Vue.js to create reactive data sources. These are key functions provided by Vue's Composition API, which is a set of additive APIs that allows flexible composition of component logic.
By the end of this tutorial, you will understand:
- What reactive()
and ref()
are
- How to use reactive()
and ref()
- Differences between reactive()
and ref()
reactive()
reactive()
function is used to create a reactive object. The reactive conversion is "deep": it affects all nested properties. In other words, if any property in the reactive object changes, Vue is aware of it and can trigger updates in the UI.
import { reactive } from 'vue'
const state = reactive({
count: 0
})
state.count++ // Vue is aware of this change
ref()
ref()
creates a reactive reference. Unlike reactive()
, the reactive conversion is "shallow". If you use ref()
with an object, Vue will not track changes in the object's properties.
import { ref } from 'vue'
const count = ref(0)
count.value++ // Vue is aware of this change
reactive()
import { reactive } from 'vue'
const state = reactive({
count: 0,
message: 'Hello, Vue!'
})
// Update a property
state.count++
console.log(state.count) // Expected output: 1
// Add a new property
state.newMessage = 'Hello, reactive!'
console.log(state.newMessage) // Expected output: 'Hello, reactive!'
ref()
import { ref } from 'vue'
const count = ref(0)
console.log(count.value) // Expected output: 0
// Update the value
count.value++
console.log(count.value) // Expected output: 1
In this tutorial, we learned about using reactive()
and ref()
, two essential functions provided by the Vue Composition API. reactive()
is used to make an object reactive, while ref()
is used to create a reactive reference.
reactive()
that includes a name
property and a message
property. Update both properties and log them to the console.Solution:
```javascript
import { reactive } from 'vue'
const state = reactive({
name: 'Vue',
message: 'Hello, Vue!'
})
state.name = 'Vue.js'
state.message = 'Hello, Vue.js!'
console.log(state.name) // Expected output: 'Vue.js'
console.log(state.message) // Expected output: 'Hello, Vue.js!'
```
ref()
. Update the reference's value and log it to the console.Solution:
```javascript
import { ref } from 'vue'
const count = ref(0)
count.value++
console.log(count.value) // Expected output: 1
```
For further practice, try creating more complex reactive objects and references. Try nesting reactive objects and references within each other and observe how Vue tracks changes.