Tips for monitoring multiple values in a Vue 3 script setup

Within my code, I currently have a watcher set up like this (inside <script setup>):

const form = reactive({
    body: '',
    image: ''
})

watch(() => form.image, () => {
    console.log(form.image)
})

I am looking to enhance this watcher by monitoring two reactive objects simultaneously:

watch(() => (form.image, form.body), () => {
    console.log(form)
})

However, it seems that only form.body is being watched now. I have attempted to follow the guidance from this question's answer, but it does not function the same way as my original watcher in terms of capturing both new and old values. My objective is for the watcher to activate only when both values are updated.

Answer №1

I made a discovery. It will activate when both conditions are met. You have the flexibility to customize the conditions as needed.

const form = reactive({
    body: '',
    image: ''
})

watch(() => [form.image, form.body], () => {
    if (form.image && form.body) {
        console.log(form)
    }
})
This approach appears effective for straightforward scenarios but may encounter issues in larger codebases with extensive use of global proxies and multiple proxies. In my experience, it worked inconsistently when tested with 4 global proxies in a complex project.

Building on @tao's suggestion in the comments, remember to include { deep: true } in your watcher configuration when dealing with nested objects.

For more information on deep watchers, refer to the Vue.js documentation.

Answer №2

To monitor multiple values simultaneously, you will need to use watch each time:

watch(() => form.image, () => {
    console.log(form.image)
})
watch(() => form.body, () => {
    console.log(form.body)
})

If you want a single watcher for both variables, do this instead:

watch([() => form.image, () => form.body], 
([newImage, newBody], [prevImage, prevBody]) => {
    console.log(form.body, form.image)
})

An example of this can be found in the following answer: from the linked question.

Answer №3

If you want to monitor reactivity, consider using the watchEffect function:

watchEffect(() => {
  emit('update:selectedProduct', localSelectedProduct.value);
  emit('update:selectedOffer', localSelectedOffer.value);
});

For more information, refer to the documentation on vuejs: https://vuejs.org/guide/essentials/watchers.html#watcheffect

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

Is there a way to transform an angular 2 app.module into ES6 format?

import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; //specific imports remov ...

How are "new" and "prototype.constructor" related in the realm of Javascript?

Many people have discussed this issue, but unfortunately, I haven't been able to find a solution yet. Here is a snippet of Javascript code regarding inheritance from a book: function Car() { var self = this; self.type = "Car" self.go = funct ...

Dormant versus dynamic PHP MySQL operations

I am facing an issue where the state doesn't change from active to inactive or vice versa when I click on it. Below is my code for ajax: <script src="//code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript"> ...

Monitor the true/false status of each element within an array and update their styles accordingly when they are considered active

Currently, I am attempting to modify the active style of an element within an array. As illustrated in the image below - once a day is selected, the styles are adjusted to include a border around it. https://i.stack.imgur.com/WpxuZ.png However, my challe ...

Tips for stopping Angular from rendering a directive that is producing incorrect results after an error is thrown

My directives have a template and a compile function that modifies the template. Occasionally, Angular fails to recognize jQuery (and defaults to using jqLite), causing my compile to encounter errors. Despite this, Angular continues to render the directive ...

What could be causing the target to malfunction in this situation?

Initially, I create an index page with frames named after popular websites such as NASA, Google, YouTube, etc. Then, on the search page, <input id="main_category_lan1" value="test" /> <a href="javascript:void(0)" onmouseover=" window.open ...

Using an AJAX request to edit a record directly without the need for a

When updating a record, I typically utilize CRUD operations and a store setup similar to the following: storeId: 'storeId', model: 'model', pageSize: 10, autoLoad: true, proxy: { typ ...

Guide to integrating Google Maps into your Vue application using vue2-google-maps

I have been trying to integrate vue2-google-maps into my app, but unfortunately, the map is not displaying as expected. Despite carefully following the documentation on how to use it, all I get is a blank white page instead of the Google Maps interface. St ...

Encountering an issue following the installation and integration of an npm module within a Meteor

I recently started a project using the latest version of Meteor. I added a new package by running the command: meteor npm install --save name_of_package Since this package is meant for the client side, I created a file called mypackage.js inside the /cli ...

Learn how to showcase vertical text in React Native similar to a drawer

Looking for a way to display text vertically in a dynamic manner, where the length of the text can vary. Below are some examples for reference: Example 1 Example 2 <View> <View style={{}}> <View style={{ marginTop: 30, flexDire ...

Is there a feature in Vue.js similar to AngularJS' `ng-repeat-start` directive?

After going through vue.js documentation, I couldn't find any reference to a feature similar to ng-repeat-start / ng-repeat-end Is there a way to achieve something like this? <table> <tr class="weather_warning top" ng-repeat-start="warni ...

How to modify the color of the placeholder text in a select dropdown using Material-ui

I have a material-ui select component that displays a dropdown menu of options for the user to choose from. The placeholder text, which currently reads "select option," appears in light grey to prompt the user to make a selection. However, I am concerned t ...

What could be causing the malfunction of the map function, despite the code appearing to be correct?

I have encountered an issue in my React functional component where I am trying to display a list of notifications. The useEffect() function is being called to generate the "data" which should then be displayed on the page. The code seems to be running fine ...

Tips for assigning a personalized value to an MUI Switch when it is in the off position

I am currently utilizing the MUI Switch component to create an On-Off button. I have manually set the value as "on" and it is functioning correctly when the switch is in the true state. However, there doesn't seem to be an option to change the default ...

How can non-numeric characters be eliminated while allowing points, commas, and the dollar sign?

Looking for an efficient method to filter out all characters except numbers, '$', '.', and ','. Any suggestions on achieving this task? ...

"Encountering an error with the any type in the useLocation feature while using React Router version 6

https://i.sstatic.net/0YcS9.png What steps should I take to resolve this particular type of error issue? My attempt at passing a custom type did not yield successful results. ...

Tips for invoking a particular function when a row in a Kendo grid is clicked

I have a Kendo grid named "mysubmissionsGrid" and I want to execute a function when each row is clicked with a single or double click. How can I accomplish this? <div class="col-xs-12 col-nopadding-left col-nopadding-right" style="padding ...

Having trouble updating values in Vue3 when accessing the next item in an object?

I'm attempting to allow my users to browse through a collection of various items. Take a look at the records object below: 0: {id: 1, pipeline_id: 1, raw: '1', completion: null, processed: 0, …} 1: {id: 2, pipeline_id: 1, raw: '2&apo ...

What is the best way to position two elements floated to the right in separate rows within a single row?

Having trouble with a web design issue. I am currently working on a website and trying to format an input field with a label so that the label sits on top of the input while floating to the right. However, I'm encountering difficulties as the elements ...

What is the best way to implement setState in this scenario?

Receiving warnings in the console that say: Avoid changing state directly. Instead, use setState() method: react/no-direct-mutation-state When I tried changing this.state.turn = this.state.turn === 'X' ? 'O' : 'X'; to this.s ...