Home > Enterprise >  Call a method on v-if inside vue.js file
Call a method on v-if inside vue.js file

Time:10-23

I am pretty new to vue.js . I have a minor issue to fix and need one help.

So I have one vue.js file which has an existing method let's say,

doSomething(){
   //updates few properties here
}

Now I have a list/array computed property let's say pageUser() , and I want to invoke doSomething whenever pageUser.length == 0.

How we can achieve this in vue.js , can we use v-if in any tag and from there can invoke the method, or what are the other ways to do this.

CodePudding user response:

You can trigger your method in 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>

  • Related