[Vuejs]-Call a method on v-if inside vue.js file

2πŸ‘

βœ…

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>

2πŸ‘

Computed properties should be side effect free. What you’re looking for is a watcher. You can watch your computed list and when its empty call the method.

watch(pageUsers, () => {
    if(pageUsers.length === 0) {
        doSomething();
    }
})
πŸ‘€Nikola Gava

Leave a comment