Leveraging Watchers on props in Vue 3's Script Setup

When passing a prop to a component that declares its state, I am attempting to watch the prop and set the CSS styling accordingly. However, for some reason it is not working as expected. Can anyone help me figure out what might be wrong?

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

  const props = defineProps({
    title: String,
    date: String,
    state: String,
  })

  let cardStatus = ref('')

  watch(props.state, () => {
    if (props.state === 'finished'){
      cardStatus.value = 'border border-success'
    }
  })
</script>

<template>
  <div :class="'bg-main-light rounded-2xl w-full p-3 lg:px-5 ' + cardStatus"></div>
</template>

Answer №1

Here's a possible solution:

observe(
  () => props.status,
  (updatedValue, previousValue) => {
    if (updatedValue === 'completed') cardState.value = 'border border-success'
  }
);

Answer №2

I've discovered a solution to get it functioning.

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

  const props = defineProps({
    title: String,
    date: String,
    state: String,
  })

  let cardStatusClass = ref('')
  
  watchEffect(() => {
    if (props.state === 'finished'){
      cardStatusClass.value = 'border border-success'
    }
  })
</script>

Answer №3

Here is my solution:

const watchProp: any = toRef(props, 'props.status');

watch([watchProp], (value) => {
    console.log(value);
    
});

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

Retrieve JSON data from Form Submission

While I am not a front end developer, I have been trying my hand at it recently. I hope that the community here can assist me with an issue I am facing. I have a form that is supposed to send files to a server-side API like shown below: <form id="uploa ...

Tips for invoking a url with JavaScript and retrieving the response back to JavaScript

I am trying to make a URL call from JavaScript with a single parameter, and the URL should respond to that specific request. Here is an example of the response format: {"success":true, "result": {"token":"4fc5ef2bd77a3","serverTime":1338371883,"expireT ...

Is there a way to make FullPage and Lightbox compatible with each other?

Currently utilizing Fullpage.js for my website, I am looking to incorporate a lightbox in one of the sections. However, upon attempting to load the script and CSS, my fullpage layout breaks and the sections collapse. I have experimented with placing the ...

Enhancing a json file on-the-fly with JavaScript/jQuery

I'm currently working with a student.json file that has this structure: { "nodes":[ {"name":"Anup"}, {"name":"Panwar"} ], "links":[ {"source":0,"target":1} ] } My objective is to receive user i ...

Is there a way to effectively organize an RSS feed using the .isoDate parameter while ensuring that the feed's elements remain interconnected (such as title and link)?

My goal is to organize the RSS feed by the most recent item while ensuring that each title corresponds correctly with its link. Currently, I am parsing and displaying the feed using the .isoDate property, but I am unsure of the best approach to achieve thi ...

Transforming an Excel document into JSON format: inspection of JSON code structure

Looking to transform Excel data into JSON format, but unsure if the current structure will be ideal for processing with D3.js. Planning to incorporate this JSON file within D3.js for visualization purposes. Here's a snippet of the Excel file: In the ...

Exploring ways to utilize removeEventListener in React Native

Can someone assist me with converting this code to React? I am new to using React and struggling with the implementation. Thank you in advance! <progress id="bar" value="0" max="110"></progress> <button onClick={i ...

apply styling to the placeholder with CSS

I have been attempting to customize the styling of the placeholder text. After setting the color to red within the input class, I did not see any changes. Even after conducting research and referring to this link Styling the placeholder in a TextField, I w ...

Discover the row and column of a selected table cell using vanilla JavaScript, no need for jQuery

In my JavaScript code, I am currently working on creating an onclick function that will display the row and column of a specifically clicked cell in a table. I have successfully implemented functionality to return the column number when the cell is click ...

Error Occurs in Vue Cli: Module '../package.json' not Found After Installation using npm

While I may not be an expert in Vuejs or Vuecli, I somehow manage to make things work. Recently, when revisiting a project I had previously worked on using Vuecli3 and webpack, I encountered the following error in development mode: $ vue-cli-service ser ...

What is preventing me from loading a module using a variable containing a string?

This code snippet demonstrates how the module can be successfully loaded using import('test'), but not with the second example. These lines of code are executed within an Angular 9 application utilizing the default Webpack configuration. var tes ...

Having trouble setting the `variant='dense'` for material-ui Toolbar – it remains at a height of 64px no matter what

Implemented a hello world AppBar/Toolbar with the variant='dense' style. import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import registerServiceWorker from './registerServiceWo ...

Unable to include a JavaScript file within another JavaScript file

Currently, I am working on a project where I am utilizing Django for the backend and HTML/CSS/JS for the frontend development. On a specific HTML page, I am including two JS files: dom_creator.js and console_page.js. My goal is to access the functionaliti ...

CSS switch status toggle

Here's my code for a toggle switch from . I'm trying to change the label before the switch/checkbox to display "checked" or "not checked" based on the toggle state. When I click on the label, it changes the switch but not the text. JavaScript: ...

Difficulty accessing Vue data passed from parent to child component

In my app.vue file, I have the parent code for a Vue app. <template> <div id="app" class="small-container"> <h1>Employees</h1> <employee-form @add:employee="addNewEmployee" /> <employee-table :employees="empl ...

Why is it not possible to isolate the function for xmlHttp.onreadystatechange?

The JavaScript file named test.js is functioning properly when included in my HTML. function sendData() { var formData = new FormData( document.querySelector("form") ); var xmlHttp = new XMLHttpRequest(); xmlHttp.open("post", "test.php",true); ...

Error: excessive recursion detected in <div ng-view="" class="ng-scope">

I've recently started learning angularJS and I've encountered an error that I need help with. Below is my index.html file: <body ng-app="myApp"> <div ng-view></div> <a href="table">click</a> <script ...

JavaScript: table is not defined

When creating a table using Django models and JavaScript, I encountered an issue where the cells values of the table could not be accessed from another JavaScript function. The error message indicated that the table was "undefined". Below is the HTML code ...

Is it possible to trigger a function dynamically upon checking a checkbox?

I’ve been working on a simple string formatting app using React, diving into hooks as I go. Right now, I’m tackling the part where I need to trigger specific text formatting functions based on checkbox selections. Let's say, if the lowercase chec ...

Learn how to extract substrings from a variable within an API using Vue.js

Exploring VueJs for the first time and looking to split a string by comma (,) retrieved from an API into separate variables. The data is coming from a JSON server. "featured-property": [ { "id": "1", " ...