Invoke a function within a v-if directive in a Vue.js script

I'm relatively new to working with vue.js and I have a small issue that I need help with.

Within my vue.js file, there is an existing method called doSomething():

doSomething(){
   //updates few properties here
}

I also have a list or array as a computed property, let's call it pageUser(), and I want to trigger the doSomething() method whenever pageUser.length == 0.

How can this be achieved in vue.js? Is using v-if in a tag a valid approach to invoke the method, or are there other methods to accomplish this?

Answer №1

To make your method trigger in a computed property:

const app = Vue.createApp({
  data() {
    return {
      user: [{id: 1}, {id: 2}],
    };
  },
  computed: {
    pageUser() {
      if (this.user.length) return this.user 
      this.doSomething()
      return 'no user'
    }
  },
  methods: {
    doSomething() {
      console.log('done something')
    },
    empty() {
      this.user = []
    }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <button @click="empty">empty</button>
  <div>{{ pageUser }}</div>
</div>

Answer №2

It is important to ensure that computed properties do not have any side effects. The solution for what you are trying to achieve is using a watcher. By watching your computed list, you can trigger a method when it becomes empty.

watch(pageUsers, () => {
    if(pageUsers.length === 0) {
        doSomething();
    }
})

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

Middleware GPS server - store location and transmit information to the server

After encountering a roadblock with my chosen GPS tracker service not supporting iframe plugins to share my car's position on my website, I've come up with the idea of creating a middleware server. The plan is to gather data from my GPS device, s ...

Comparing Buffer and Uint8Array in Node.js

Exploring the documentation for the fs module 1, we come across the following regarding the writeFile method: const data = new Uint8Array(Buffer.from('Hello Node.js')); Further in the documentation 2, it states: With TypedArray now available, ...

The v-menu closes before the v-list-item onclick event is detected

I have set up the following menu using vue and vuetify: <div id="app"> <v-app id="inspire"> <div class="text-center"> <v-menu> <template v-slot:activator="{ on }"> ...

React - Object(...) is throwing an error because it is not a function or the value it is returning cannot be

I have encountered an issue with my React hook that wraps a class component. I am attempting to pass a state from this hook to the class component using useEffect, but I keep receiving the following error: TypeError: Object(...) is not a function or its r ...

Issue with redux that causes components to not re-render when they are placed inside an "OnClick" event

Apologies for my limited English skills, but I am currently working with React and Redux. Here is the React code: import gsap from "gsap"; import { useGSAP } from "@gsap/react"; import githubLogo from "../assets/github.png"; i ...

The Angular reactive form is being submitted without completing the submission process

I've been working on an Angular 5 reactive form and everything seems to be functioning correctly. However, I've encountered a strange issue with a button used to close the form by hiding it from view. Whenever I click on this close button, the f ...

What is the method for setting a variable to an object property's value?

I am currently working on a React app and I have an object structured like this: state = { property1: 'value', property2: 'value', property3: 'value', property4: 'value', } I am trying to write a fu ...

Saving form data with a tinymce textarea, radio button, and checkbox to the database

My form contains multiple textarea fields, radio buttons, checkboxes, and a select input. Initially, I was able to submit the form using PHP without any issues. However, when I integrated TinyMCE with one of the textareas, I had to introduce JavaScript to ...

Leverage i18n-2 within Node.js without utilizing the res scope

Is there a way to utilize i18n within functions that are called? I am currently facing an error: (node:15696) UnhandledPromiseRejectionWarning: TypeError: i18n.__ is not a function How can I ensure that i18n will work inside functions without having to b ...

Vue: Implementing conditional styling in table cells

Currently, my vue function involves using nested v-for loops to iterate through an object and create a table with rows and cells. While this method is effective, I am now faced with the challenge of implementing a v-if statement in the innermost loop to co ...

How do I programmatically switch the Material-UI/DatePicker to year view in React?

I have a DatePicker component set up in my project, and it works perfectly fine. However, for my specific use case, I only need the year view to be displayed. Within the child component of the DatePicker (Calendar), there is a function called: yearSelect ...

The directives applied within ng-include are not functioning correctly

Below is a custom directive I have implemented. var fancySelectDirective = pluginDirecitvesModule.directive("custom-select",function(){ return { restrict: 'C', link: function (scope, element, attrs) { ...

Creating a PNG file from a Uint8Array containing RGBA data

I am currently attempting to save a screenshot of a specific area in ThreeJS to a file. Initial attempts involved displaying the image in a new tab using: window.open(renderer.domElement.toDataURL("image/png")); The renderer object used has preserveDrawi ...

Is it possible to prevent any actions from occurring in Vuex until the state is fully prepared?

Currently, I am facing an issue while performing a fetch request inside an action during the creation step of one of my components. The problem arises when I require certain parameters from the state to execute the fetch, as upon reloading the page, the ...

How can you transfer data from a Writable Buffer to a ReadStream efficiently?

How do I convert a writable stream into a readable stream using a buffer? This is my code to store data from an ftp server in an array of chunks: let chunks = [] let writable = new Writable writable._write = (chunk, encoding, callback) => { chunks.p ...

Developing a server-side checkbox feature and implementing a corresponding JavaScript function

After dynamically creating a checkbox on the server-side and populating it in a table on the webpage, I want to utilize it to trigger some JavaScript functions on the client side. However, I'm unsure of how to activate the function using a checkbox c ...

Error in TypeScript while running the command "tsd install jquery" - the identifier "document" could not be found

Currently, I am facing an issue with importing jQuery into my TypeScript project. In order to achieve this, I executed the command tsd install jquery --save, which generated a jquery.d.ts file and added /// <reference path="jquery/jquery.d.ts" /> to ...

Is there a way to mock a "find" call in mockingoose without getting back "undefined"?

I am currently working with mockingoose 2.13.2 and mongoose 5.12.2, leveraging Typescript and jest for testing purposes. Within my test scenario, I am attempting to mock a call to my schema's find method. Here is what I have tried: import mockingoose ...

Issue with Loosing Focus in React TextInput when typing the letter "S"

My TextInput is acting strangely - it loses focus only when I type the letter s. All other letters work fine. <FormControl key={"1"} sx={{ m: 1 }} variant="outlined" onChange={handleFilterValueChange}> <InputLabel htmlFor=& ...

What are some ways to optimize the efficiency of handling a sizable JSON object in React Native?

I am currently developing an application using React Native and have encountered significant slowdowns during transitions when loading more data. I am exploring alternative app structuring methods to prevent these performance issues, especially as the JSON ...