Skip to content
Advertisement

How to run method when a div re-init – Vuejs

I try

<div v-if="isRun" v-html="myMethod"></div>
<div v-else v-html="myMethod2"></div>

computed: {
  myMethod: function() {
    alert('1');
  },
  myMethod2: function() {
    alert('2');
  },
}

and isRun variable’s change dynamic (switch by user) and i want myMethod and myMethod2 re-run when div re-init.

But I try with v-html it only run first time.

How to do that. thank.

Advertisement

Answer

So if you are strictly want to use this methods, computed properties watch their dependencies for changes before they get updated, from the docs

You can data-bind to computed properties in templates just like a normal property. Vue is aware that vm.reversedMessage depends on vm.message, so it will update any bindings that depend on vm.reversedMessage when vm.message changes. And the best part is that we’ve created this dependency relationship declaratively: the computed getter function has no side effects, which makes it easier to test and understand.

Here is a simple hack for your needs, there is better ways for this approach

new Vue({
    el: "#app",
  data:{
    isRun: true,
  },
  computed: {
    myMethod: function() {
        this.isRun == this.isRun // it doesn't really depend on this.isRun but vue thinks it does
        alert('1');
    },
    myMethod2: function() {
        this.isRun == this.isRun
      alert('2');
    },
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.min.js"></script>
<div id="app">
  <div v-if="isRun" v-html="myMethod"></div>
  <div v-else v-html="myMethod2"></div>
  
  
  <button @click="isRun = !isRun">Toggle</button>
</div>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement