Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue3 Watch Property

Vue3 Watch Property

In this chapter, we will introduce the Vue3 watch property. watch, we can use watch to respond to changes in data.

watch is used to monitor changes in reactive properties and execute specific operations when the property changes. It is a reactivity mechanism in Vue that allows you to respond accordingly when data changes and execute custom logic.

watch This gives you more control and flexibility when reactive properties change, allowing your components to better respond to data changes and execute the corresponding logic.

The following example implements a counter using watch:

Example

<

div id

=

"app"

   

<

p style

=

"font-size:25px;"

Counter

:

{

{

counter

}

}

p

   

<

button

@

click

=

"counter++"

style

=

"font-size:25px;"

Click me

button

div

   

<script const app={data(){return{counter>

:

1

   

}

 

}

}

vm

=

Vue.

createApp

(

app

)

.

mount

(

'#app'

)

vm.$watch

(

'counter'

,

function

(

nval

,

oval

)

{

    alert

(

'Counter value changed to: '

oval

' changed to '

nval

'!'

)

;

}

)

;

script

Try it »

The following example performskilometersThe difference betweenmetersconversion between:

Example

<

div id

=

"app"

    kilometers

:

<

input type

=

"text"

v

model

=

"kilometers"

 

@

focus

=

"currentlyActiveField = 'kilometers'"

    meters

:

<

input type

=

"text"

v

model

=

"meters"

@

focus

=

"currentlyActiveField = 'meters'"

div

<

p id

=

"info"

p

   

<script const app={data(){return{kilometers>

:

0

,

      meters

:

0

   

}

 

}

,

  watch

:

{

    kilometers

:

function

(

newValue

,

oldValue

)

{

     

// Check if it is the current input box

     

if

(

this

.

currentlyActiveField

===

'kilometers'

)

{

       

this

.

meters

=

newValue

1000

     

}

   

}

,

    meters

:

function

(

newValue

,

oldValue

)

{

     

// Check if it is the current input box

     

if

(

this

.

currentlyActiveField

===

'meters'

)

{

       

this

.

kilometers

=

newValue

/

1000

;

     

}

   

}

 

}

}

vm

=

Vue.

createApp

(

app

)

.

mount

(

'#app'

)

vm.$watch

(

'kilometers'

,

function

(

newValue

,

oldValue

)

{

 

// This callback will be called after vm.kilometers changes

  document.

getElementById

(

"info"

)

.

innerHTML

=

"Value before change: "

oldValue

", value after change: "

newValue

;

}

)

script

Try it »

Click the "Try it" button to view the online example

In the code above, we created two input boxes. In the data property, kilometers and meters both start with an initial value of 0. The watch object creates two watcher methods for the data object: kilometers and meters.

When we enter data in the input boxes, watch listens to the data changes in real time and updates its own value. You can see the video demonstration below:

Using watch in asynchronous loading

For loading asynchronous data, Vue provides a more general method through the watch option to respond to data changes.

In the following example we use the axios library, which will be introduced in detail later.

Example

<

script src

=

"https://cdn.staticfile.org/axios/0.27.2/axios.min.js"

script

<

script src

=

"https://cdn.staticfile.org/vue/3.2.37/vue.global.min.js"

script

<

script

const

watchExampleVM

=

Vue.

createApp

(

{

    data

(

)

{

     

return

{

        question

:

''

,

        answer

:

'Each question must end with a ? mark.'

     

}

   

}

,

    watch

:

{

     

// This function runs whenever the question changes; it ends with a ? to support both Chinese and English questions.

      question

(

newQuestion

,

oldQuestion

)

{

       

if

(

newQuestion.

indexOf

(

'?'

)

1

||

newQuestion.

indexOf

(

'?'

)

1

)

{

         

this

.

getAnswer

(

)

       

}

     

}

   

}

,

    methods

:

{

      getAnswer

(

)

{

       

this

.

answer

=

'Loading...'

        axios

          .

get

(

'/try/ajax/json_vuetest.php'

)

          .

then

(

response

=>

{

           

this

.

answer

=

response.

data

.

answer

         

}

)

          .

catch

(

error

=>

{

           

this

.

answer

=

'Error! Unable to access the API. '

error

         

}

)

     

}

   

}

 

}

)

.

mount

(

'#watch-example'

)

script

Try it »


Summary of Usage

watch is a reactive data listening mechanism provided by Vue 3 that can watch a single or multiple properties.

You can handle data changes by passing a callback function, with options such as deep watching and immediate execution supported.

1. Basic Usage

In Vue 3, the watch function is used to watch reactive properties.

When the watched property value changes, Vue triggers the callback function to execute.

Example

import

{

reactive

,

watch

}

from

'vue'

;

export

default

{

  setup

(

)

{

   

const

state

=

reactive

(

{

      count

:

0

   

}

)

;

    watch

(

     

(

)

=>

state.

count

,

// The property being watched

     

(

newVal

,

oldVal

)

=>

{

// The callback function on change

        console.

log

(

`count changed from $

{

oldVal

}

to $

{

newVal

}

`

)

;

     

}

   

)

;

   

return

{

      state

   

}

;

 

}

}

;

2. Watching Multiple Reactive Properties

If you want to watch multiple reactive properties at the same time, you can pass them as an array:

Example

import

{

reactive

,

watch

}

from

'vue'

;

export

default

{

  setup

(

)

{

   

const

state

=

reactive

(

{

      count

:

0

,

      name

:

'Vue3'

   

}

)

;

    watch

(

     

[

(

)

=>

state.

count

,

(

)

=>

state.

name

]

,

// Watch multiple properties

     

(

[

newCount

,

newName

]

,

[

oldCount

,

oldName

]

)

=>

{

        console.

log

(

`count changed from $

{

oldCount

}

to $

{

newCount

}

`

)

;

        console.

log

(

`name changed from $

{

oldName

}

to $

{

newName

}

`

)

;

     

}

   

)

;

   

return

{

      state

   

}

;

 

}

}

;

3. Deep Watching

If you are watching an object or array and want to watch its nested properties, you can use the deep: true option. This watches all property changes of the object.

Example

import

{

reactive

,

watch

}

from

'vue'

;

export

default

{

  setup

(

)

{

   

const

state

=

reactive

(

{

      user

:

{

        name

:

'Alice'

,

        age

:

25

     

}

   

}

)

;

    watch

(

     

(

)

=>

state.

user

,

// Watch the entire object

     

(

newVal

,

oldVal

)

=>

{

        console.

log

(

'User object changed:'

,

newVal

,

oldVal

)

;

     

}

,

     

{

deep

:

true

}

// Enable deep watching

   

)

;

   

return

{

      state

   

}

;

 

}

}

;

4. Immediate Execution

By default, watch only triggers the callback when the watched value changes. If you want the callback to execute immediately when the component loads, set immediate: true.

Example

import

{

reactive

,

watch

}

from

'vue'

;

export

default

{

  setup

(

)

{

   

const

state

=

reactive

(

{

      count

:

0

   

}

)

;

    watch

(

     

(

)

=>

state.

count

,

// Watch a property

     

(

newVal

,

oldVal

)

=>

{

        console.

log

(

`count changed from $

{

oldVal

}

to $

{

newVal

}

`

)

;

     

}

,

     

{

immediate

:

true

}

// Execute immediately

   

)

;

   

return

{

      state

   

}

;

 

}

}

;

5. Asynchronous Operations

If you need to perform asynchronous operations in watch, you can use async and await directly in the callback function, which lets you handle operations such as API requests and data storage.

Example

import

{

reactive

,

watch

}

from

'vue'

;

export

default

{

  setup

(

)

{

   

const

state

=

reactive

(

{

      count

:

0

   

}

)

;

    watch

(

     

(

)

=>

state.

count

,

      async

(

newVal

,

oldVal

)

=>

{

        console.

log

(

`count changed from $

{

oldVal

}

to $

{

newVal

}

`

)

;

       

// Assume an asynchronous request is made

        await fetch

(

`https

:

//api.example.com/count/${newVal}`);

     

}

   

)

;

   

return

{

      state

   

}

;

 

}

}

;

6. Watching Multiple Properties with a handler Function

You can also use watch as a handler for multiple properties, like this:

Example

import

{

reactive

,

watch

}

from

'vue'

;

export

default

{

  setup

(

)

{

   

const

state

=

reactive

(

{

      count

:

0

,

      name

:

'Vue3'

   

}

)

;

   

const

handler

=

(

[

newCount

,

newName

]

,

[

oldCount

,

oldName

]

)

=>

{

      console.

log

(

`count changed

:

$

{

oldCount

}

→ $

{

newCount

}

`

)

;

      console.

log

(

`name changed

:

$

{

oldName

}

→ $

{

newName

}

`

)

;

   

}

;

    watch

(

[

(

)

=>

state.

count

,

(

)

=>

state.

name

]

,

handler

)

;

   

return

{

      state

   

}

;

 

}

}

;

7. watchEffect: A Simplified Watcher

Vue 3 also provides the watchEffect API, which is more concise than watch and automatically tracks changes in reactive data without needing to specify a data source.

Example

import

{

reactive

,

watchEffect

}

from

'vue'

;

export

default

{

  setup

(

)

{

   

const

state

=

reactive

(

{

      count

:

0

   

}

)

;

    watchEffect

(

(

)

=>

{

      console.

log

(

`count is

:

$

{

state.

count

}

`

)

;

   

}

)

;

   

return

{

      state

   

}

;

 

}

}

;

watchEffect automatically detects changes in state.count and triggers the callback when it changes.

8. The flush Option

The flush option is used to control when the watch callback executes.

By default, the watch callback executes after the DOM is updated. If you need the callback to execute before the update, you can use flush: 'pre'.

Example

import

{

reactive

,

watch

}

from

'vue'

;

export

default

{

  setup

(

)

{

   

const

state

=

reactive

(

{

      count

:

0

   

}

)

;

    watch

(

     

(

)

=>

state.

count

,

     

(

newVal

,

oldVal

)

=>

{

        console.

log

(

`count changed from $

{

oldVal

}

to $

{

newVal

}

`

)

;

     

}

,

     

{

flush

:

'pre'

}

// Execute the callback before the update

   

)

;

   

return

{

      state

   

}

;

 

}

}

;