Initiate function directly through computed property (Vue.js)

I'm currently working on a project using Vue 3 along with VueX.

I am wondering if there is a way to check within the computed property whether the value returned is true, and then directly trigger my method without needing a watcher.

A bit of background: The value of this.$store.state.boolean changes occasionally, so I need to trigger my method if it becomes true.

Below is an example of how I am currently handling this:

//computed
computed: {
  test() {
    return this.$store.state.boolean;
  },
}

//watch
watch: {
  test(boolean) {
    if (boolean == true) {
      this.trigger_method();
    }
  }
},

//methods
method: {
  trigger_method() {
    console.log("TEST");
  }
}

Answer №1

Avoid having side effects in your computed functions, as explained here: https://vuejs.org/guide/essentials/computed.html#getters-should-be-side-effect-free

To address your query, consider the following code snippet:

//computed
computed: {
  test() {
    if (this.$store.state.boolean) {
      this.trigger_method();
    }

    // Make sure to return a value since this is a getter function.
    return this.$store.state.boolean;
  },
}

For your issue, I suggest the following approach:

watch: {
  '$store.state.boolean': function() {
    if ($store.state.boolean === true) {
      this.trigger_method();
    }
  }
}

If you don't require the computed function for a specific component, you could establish a subscriber for your Vuex Store using this guide: https://vuex.vuejs.org/api/#subscribe

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

When using v-for to render components and <selection>, is there a way to customize it for just one specific instance of the component?

How can I modify the selection in each instance separately when rendering elements of an array obtained from the backend using v-for? Currently, changing one selection affects all instances due to the v-model. Is there a way to target only one selection ...

Customizing the background color of an option using HTML and CSS

I am currently developing an option form where each selection will appear in a different color as the user scrolls down. Once a selection is made, it should be saved and displayed with the chosen color. https://i.sstatic.net/gvdpt.png My goal is to save ...

Is there a way to make res.render in node.js/express/mongo wait until the database search is finished before loading?

Having some difficulty with loading a table properly on my page because the information is not being passed to the ejs template before the page loads. I'm fairly new at this and could use some assistance! Just a heads up, owneditems consists of an ar ...

JavaScript Failing to Validate User Input in Form

I'm a beginner in JavaScript and I'm trying to validate a simple date of birth input, but for some reason, it seems that the JavaScript file is not working. No matter what I input, it always goes through, so I'm trying to figure out what&apo ...

Extract information from one webpage, proceed to the following page, and repeat the process, utilizing JavaScript on the site

Exploring various web scraping techniques, I've hit a roadblock and could use some assistance. Currently, my Python code successfully extracts data from the first page of my website. response = requests.get(url) soup = BeautifulSoup(r.text, 'ht ...

What could be causing the QullJS delta to display in a nonsensical sequence?

The outcome showcased in the delta appears as: {"ops":[{"retain":710},{"insert":" yesterday, and she says—”\n“The clinic?","attributes":{"prediction":"prediction"}},{"del ...

HtmlButton failing to execute client-side validation on IE11

I am encountering a strange problem with a web form using the HTMLButton in an asp.net environment. Due to formatting requirements, I need to utilize a <button> construct which functions properly in all browsers except for IE11. <button id="cmdLo ...

Troubleshooting a unique CSS bug in jQuery mouseover functionality

Check out this pen: https://codepen.io/anon/pen/eKzEVX?editors=1111 I recently created a Form Select in Laravel: {!! Form::select('status_id', $statuses, $post->status_id, ['class' => 'form-control post-sub-items-label &apo ...

Converting Dates with Ractive.js

Is there a way to transform the Epoch time value retrieved from a JSON endpoint into a readable time string format such as "Tue 19 Jan 11:14:07 SGT 2038" without relying on external libraries like moment.js? var ractive = new Ractive({ el: '#cont ...

How can I dynamically generate multiple Reactive Forms from an array of names using ngFor in Angular?

I am in the process of developing an ID lookup form using Angular. My goal is to generate multiple formGroups within the same HTML file based on an array of values I have, all while keeping my code DRY (Don't Repeat Yourself). Each formGroup will be l ...

Sorting dates and amounts in string format with Smart-table

Sorting is a breeze in smart-table, but what about when the date and amount are in string format? How can we sort them? app.controller('basicsCtrl', ['$scope', function (scope) {scope.rowCollection = [ {firstName: 'Laurent', ...

I seem to be encountering an issue while looping through an array of objects. Instead of retrieving all two elements, only one object is being returned. Can

Just a heads up, I'm new to coding so please bear with me. I'm attempting to run through the "diary" array and the function "howMany" is only showing 2 'Home' elements, although there are actually 4 'Home' elements in total i ...

Submenu animation that "bursts onto the scene"

I'm facing an issue with my menu that has sub-items inside it. To achieve the animation effect I desire, I need to extract the width, height, and first-child's height of the sub-menu. While my animation is working most times, there are instances ...

Merge the values of two select tags into a single textbox

There are two select Tags along with a text box included. <select name="select1"> <option>1</option> <option>2</option> </select> <select name="select2"> <option>1</option> <option>2 ...

dojo.js is throwing a multipleDefine error when using qwest.js

Having some trouble loading qwest.js with the dojo (ArcGIS) AMD loader, encountering a multipleDefine error. require([ // `../vendor/react/react.js`, // this works fine `../vendor/qwest/qwest.min.js`, // this causes error ], ( // React, qwest, ) ...

Is there a one-liner to efficiently eliminate all instances of a specific sub-string from an array using the filter

In search of a solution to filter an array and eliminate all instances of substrings, similar to removing entire strings as shown below: const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"] x= x.filter(i ...

Configuring Systemjs to properly load the templateUrl in Angular2ORSetting

I am facing an issue with systemjs while working with angular2. index.html System.config({ packages: { 'app': { format: 'register', defaultExtension: 'js' }, 'an ...

Is it possible to extend the Object class in order to automatically initialize a property when it is being modified?

My experience with various programming languages leads me to believe that the answer is likely a resounding no, except for PHP which had some peculiar cases like $someArray['nonexistentKey']++. I'm interested in creating a sparse object whe ...

Node.js callback functions are a crucial part of the program's operation. It can be frustrating when a TypeError occurs, such as when trying

Currently, I am grappling with the concept of callbacks. Can someone clarify why I am facing difficulties updating my webpage using the callback from setInterval? Upon running the code, I encounter the following error: /home/pi/Programming/RC Car/server_ ...

There was an error connecting to Pusher on the staging environment, yet everything seems to be functioning properly on localhost

Recently encountered an error on the staging server while trying to broadcast a message using Pusher: staging.ERROR: Failed to connect to Pusher. {"exception":"[object] (Illuminate\\Broadcasting\\BroadcastException(code: ...