Is it possible to monitor a particular attribute of an object in Vue 3?

Here you can find a method in the documentation for watching an entire reactive object as shown below:

const state = reactive({ 
  id: 1, 
  name: "",
});

watch(
  () => state,
  (state, prevState) => { // ...
  }
);

But what if you only need to monitor changes in the name property?

watch(state.name, (name, prevName) => {
    // For example: trigger a server-side request for occupation validation
});

The code snippet above needs correction.

Answer №1

If you want to observe and track the modification of a specific attribute, you can achieve it like this:

const data = reactive({
  id: 1,
  name: ""
});

watch(
  () => data.name,
  (newName, prevName) => {
    /* Code for handling the change */
  }
);

Answer №2

watch: {
    'state.name': function () {
         // updated...
    }
}

We hope that this solution resolves the issue for you.

Answer №3

Observing a getter for a property of an object. Here's an illustration showcasing how to declare objects using reactive() and ref().

vue playground

<script setup>
import { ref, reactive, watch } from 'vue'

const msg = ref('Hello World!')

const state1 = reactive({ id: 1, name: "your-name-reactive" })
const state2 = ref({ id: 2, name: "your-name-ref" })

const testingField1 = ref('')
const testingField2 = ref('')
const testingField3 = ref('')

watch(
  () => state1.name,
  (newName, prevName) => {
    testingField1.value = newName
  }
)

watch(
  () => state2.value.name,
  (newName, prevName) => {
    testingField2.value = newName
  }
)

watch(
  [() => state1.name, () => state2.value.name],   // ⬅️
  () => {
    testingField3.value = `was triggered by any one at ${new Date().toLocaleString()}`
  }
)
</script>

<template>
  <h1>{{ msg }}</h1>
  <div>
    <input v-model="state1.name" />
    <button @click="state1.name = new Date().toLocaleString()">click me</button>
    <span>{{ testingField1 }}</span>
  </div>
  <div>
    <input v-model="state2.name" />
    <button @click="state2.name = new Date().toLocaleString()">click me</button>
    <span>{{ testingField2 }}</span>
  </div>
  <div>
    <span>{{ testingField3 }}</span>
  </div>
</template>

It is important to note the usage of .value when initializing an object with ref().

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

Creating a .post request using Axios in VueJS and Nuxt

I am a beginner in web development and I have a question regarding creating a .post using Axios with Nuxt. What I need help with is creating a button that will send three inputs to the NodeJS app. <template> <div class="container"&g ...

Tips on duplicating objects in TypeScript with type annotations

My goal is to inherit properties from another object: interface IAlice { foo: string; bar: string; }; interface IBob extends IAlice { aFunction(): number; anotherValue: number; }; let alice: IAlice = { foo: 'hi', bar: 'bye&apo ...

Nested formArrays within formArrays in Angular 4

I've been working on implementing a FormArray inside another FormArray, but it doesn't seem to be functioning correctly. I also tried the solution provided in the link below, but it didn't work for me. How to get FormArrayName when the Form ...

Issue with Vue.js app display within Chrome extension

I have encountered an issue while trying to run a Vuejs app in a Chrome extension as a new tab. The app renders perfectly fine when running it from the dist/ folder using simplehttpserver dist/. However, when I attempt to load the dist folder as a Chrome E ...

Can you explain the significance of the | symbol in TypeScript?

My journey with TypeScript is just beginning, and I recently encountered the symbol | while working on a problem in LeetCode using Typescript. I believe it has something to do with defining variable types. Can anyone provide more insight into this? /** ...

Challenges with Vue and the <noscript> element

I recently deployed a vue app and everything seems to be functioning as expected. However, I encountered an issue when trying to view the page source in any browser - the actual content is not visible and instead, the body section starts with a message ins ...

Electron does not have the capability to utilize Google's Speech to Text engine

I am trying to connect my microphone with the Google Speech to Text engine. I came across this page and copied the code into my renderer.ts file, uncommented the lines with const, but when I run it, I encounter an error at line 7 (const client = new speech ...

Leverage the power of Laravel's Blade.php templating engine by incorporating JavaScript code compiled with

How can I incorporate a JavaScript function in my blade.php file? I have created xyz.js with a simple function: function picture(something){ document.getElementById('idXYZ').src = "example.com"; } Next, I added this file to the webpack.mix. ...

VeeValidate 4: Analyzing Field Validation Status

Trying to replicate the style of Bootstrap form validation using Vue and Vee-validate has been a challenge for me. To achieve the Bootstrap validation error message behavior, it's crucial that the input displays the class is-invalid when there is a v ...

Oops! An issue occurred: Attempting to access 'handle' property of an undefined value

Within my application, I've developed two distinct components: the Selector Component and the Shifter Component. The Selector Component is responsible for selecting a list of items that require updating, and it triggers a method in the Shifter Compone ...

Is there a way for me to program the back button to navigate to the previous step?

I am currently developing a quiz application using a JSON file. How can I implement functionality for the back button to return to the previous step or selection made by the user? const navigateBack = () => { let index = 1; axios.get('http ...

Changing the order of a list in TypeScript according to a property called 'rank'

I am currently working on a function to rearrange a list based on their rank property. Let's consider the following example: (my object also contains other properties) var array=[ {id:1,rank:2}, {id:18,rank:1}, {id:53,rank:3}, {id:3,rank:5}, {id:19,r ...

Continuously running the beforeMount hook in Vue3

Greetings and Happy Holidays! I'm facing a little issue in my Vue3 application. When I use a beforeMount without a child component, everything works perfectly fine. The code runs only once and the page displays as expected. However, when I introduce ...

Tips for resolving the issue of "The types 'GameState' and 'string' do not intersect, so this condition will always yield 'false'."

I need to display different components based on the value of gameStatus: import React from "react"; import { useAppSelector } from "./hooks/redux"; import EndScreen from "./pages/EndScreen"; import QuestionsPage from "./p ...

GraphQL type featuring a union property defined inline

Trying to create a matching GQL type for this Typescript interface: interface List { items: [String] | [[String]] } Initially, I attempted to keep it straightforward: type List { items: [String]! | [[String]!]! } However, GQL did not approve of tha ...

What is the method for determining the type of a TypeScript class member that is associated with a commonly used symbol such as Symbol.toStringTag?

Does anyone know the correct TS syntax for extracting the type of a class method indexed with a well-known Symbol? Here are two incorrect methods: type T = String[Symbol.toStringTag]; // 'Symbol' only refers to a type, but is being used as a name ...

RC6 - What is the significance of encountering an 'Unexpected token <' error message?

After updating to RC.6, I am encountering a series of errors related to third-party components. Specifically, the error message displayed is: SyntaxError: Unexpected token <. This issue has arisen with ng2-bootstrap, ng2-select, and angular2-jwt. Howev ...

What is the best way to create a data type that enables unrestricted index retrieval while ensuring that the value retrieved will never be

By enabling the noUncheckedIndexedAccess option in TypeScript, we ensure that when accessing object properties with arbitrary keys, the value type includes both the specified type and undefined. This behavior is generally appropriate as it aligns with run ...

Can someone please explain how to display a specific element from a JSON Array?

Is there a way to display only this specific part? /db/User_DataDb/61500546-4e63-42fd-9d54-b92d0f7b9be1 from the entirety of this Object obj.sel_an: [ { "__zone_symbol__state":true, "__zone_symbol__value":"/db/User_DataDb/61500546-4 ...

Having trouble getting webpack to transpile typescript to ES5?

Despite following official guides and various tutorials, I am still facing an issue with compiling my code to ES5 using TypeScript and webpack. The problem is that the final bundle.js file always contains arrow functions. Here is a snippet from my webpack ...