Setting a data value once the v-if condition has been fulfilled

Looking to accomplish a seemingly simple task, but struggling to find a native solution. I have multiple divs on a page with v-if conditions acting as filters for data (similar to filtering a table by select boxes).

Here's a basic example: I want to assign a variable in my data object once a v-if condition is met. If the filters change and a different condition is satisfied, I want to update the same variable with a new value.

I need a dynamic value that can be updated based on any page filters, as long as I can modify it after a v-if condition is met.

My hope was to simply call a method with an argument once a v-if is resolved.

var vm = new Vue({
  el: "#app",
  props: { 

  },
  data: {
    showData: 'ABC',
    specificData: "here are some specifics",
    newValue: ''
    
  }
  });
<div id ="app">
<div v-if="showData === 'ABC'">
  <!--Here, I want to set newValue to something like 'ROGER' unrelated to ABC-->
  ABC
</div>

<div v-if="showData === '123'">
  <!--Here, I want to set newValue to something like 'SAM' unrelted to 123-->
  123
</div>
</div>

Answer №1

It's important to note that handling this type of business logic in a template is not recommended; it should be handled in a computed property instead. A basic implementation may look like this:

data(){
  return {
    showData: "ABC"
  }
},
computed: {
  newValue(){
    if (this.showData === "ABC") {
      return "Some derived value"
    }
    return ''
  }
}

Another approach is to utilize a watcher on showData and trigger additional methods based on certain conditions being met.

watch: {
  showData(val){
    if (val === "ABC") {
      this.newValue = "Some derived value"
      this.someOtherMethod()
    }
    // Additional conditions can be checked here
    // or pass the value to another method where all checks are performed
    this.checkValue(val)
  }
}

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

Custom ID in Firebase Firestore is not generating a new document even after successfully creating a new user

In my Vue App, I designed a registration form to automatically create a Firestore document linked to the User UID with a unique document ID. Although the user creation process is successful, the document creation fails without showing any errors in the c ...

Modify the output information in a VueJS dropdown menu

I have a VueJS multiselect component that is displaying data from a JSON file using axios. Unfortunately, I am unable to modify the data directly. However, I would like to edit the text displayed and hide any blank entries. For example, I want 'BL&ap ...

What's the best way to ensure a div's height and width are equal when implementing responsive design?

I am currently working on a responsive design and facing challenges in making div's height and width equal. Initially, I set the div's width as a percentage and height as auto, but this caused the divs to not display properly. To resolve this iss ...

Experience the power of VueJS 3 with Pinia, all without the need

I've hit a wall. Despite scouring documentation and countless google searches, I can't seem to find the answer to this straightforward query: how do I install/import PINIA in a VUE application? Let's consider a basic VUE app: <div id=&qu ...

Issue with state not being updated upon clicking "Save" button

After setting multiple items in the TransferList component provided by Material-UI, I am encountering an issue when trying to update a state upon clicking "Save". The problem is that the state does not update immediately after clicking "Save"; it requires ...

Can a nodeJS script be written to automate selecting options and filling out forms in HTML?

Greetings everyone, I am new here so please excuse me if my formatting is not up to par. Currently, I am tackling a project for an internship and after some extensive research, I am stumped on how to automate certain reports in the next phase. In summary ...

Explore the Benefits of Using MUI V5 Grid Component for Your Box Design

Exploring MUI to delve into the world of React for the first time. Curious about the usage of the Box component alongside the Grid component. The example on the docs showcases this scenario. export default function BasicGrid() { return ( <Box sx={ ...

Difficulty Showing Leading Digit on JavaScript Timepiece

Recently, I've been dabbling in creating a basic stopwatch script using JavaScript to showcase the elapsed seconds, minutes, and hours. The desired time format is: hh:mm:ss In my quest to achieve this with JavaScript, I encountered a roadblock. The ...

Stop Code Execution || Lock Screen

Is there a way to address the "challenge" I'm facing? I'm an avid gamer who enjoys customizing my game using JavaScript/jQuery with Greasemonkey/Firefox. There are numerous scripts that alter the DOM and input values. In my custom script, I hav ...

What is the best way to display the selected value of a radio button in React Native?

Being relatively new to React Native and mobile app development in general, I am facing an issue while trying to display the values assigned to different radio buttons within a radio button group. My code snippet is provided below: RadioButtons.js im ...

Encountering issues with properly updating the Vuex store

Looking at my Vuex 2 store: const datastore = new Vuex.Store({ state: { socketcluster: { connection: false, channels: [] }, selected_offers: [] }, mutations: { addOffer: function(offer) { datastore.state.s ...

Enhancing React Components using Variable State Management

Having trouble updating my state while trying to use the NASA API. The Axios function for calling the API is working smoothly. Currently, the default state of datePicked is empty, so the GET request defaults to the current date. I'm now working on add ...

Tips for resolving the issue of "Warning: validateDOMNesting(...): <div> cannot be a child of <tbody>"

Users list is passed as a prop to the UserItem Component in order to iterate over the user list and display them on a table. The list is being displayed correctly, and there are no divs in the render return, but an error persists: tried many solutions fou ...

Dynamic loading can be followed by compiling the less file

For each component on my website, I have a separate LESS file where I import the necessary styles and controls. My goal is to compile the LESS file after it has been loaded. Here is an example of how the HTML code looks: <link rel="stylesheet/less ...

The .forEach() method in Javascript is not suitable for DOM nodes as they are subject to change during the iteration

Having an issue with moving all DOM elements from one node to another, I initially used this code: div.childNodes.forEach((n) => me.container.appendChild(n)); However, I noticed that only half of the nodes were being copied. It seems that the problem ...

Tips for displaying HTML content in an AJAX success alert message with ASP.NET MVC and jQuery

I have an action result that sends content in the following format: public ActionResult MyAction() { string mystring = //doing something return Content(mystring , "html"); } Client Side: $.ajax({ url: "/MyController ...

The custom validation in Node.js using Express-Validator is ineffective

I have implemented custom validators using express-validator to include specific validations: middlewares.js module.exports = function (app) { console.log('making sure I am being called'); return function (request, response, next) { ...

"Upon pressing the submit button in the router.post function, a null value appears

In my form, I am attempting to redirect the page to the home URL after clicking the submit button. However, using res.redirect('/home') is not achieving the desired result. I have also tried using console.log("testing");, but that is not working ...

Error: The function $(...).ekkoLightbox is not defined

Recently, I attempted to integrate ekkolightbox into my WordPress website. However, each time I selected an image, I encountered the following error message: Uncaught TypeError: $(...).ekkoLightbox is not a function Initially, I suspected that the issue ...

Tips on searching for an entry in a database with TypeScript union types when the type is either a string or an array of strings

When calling the sendEmail method, emails can be sent to either a single user or multiple users (with the variable type string | string[]). I'm trying to find a more efficient and cleaner way to distinguish between the two in order to search for them ...