Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

vuejs to trigger one of 3 potential methods based off of data

I want to trigger one of 3 methods based on what data is found in subdescription. As of now it works fine if the data is "Video" and if anything else, it triggers the myClick2 method. I am trying to add a 3rd option in that checks to see if it says "Poster". If it says poster, to trigger another method (myClicky). Anything else, show the myClick2.

new Vue({
  el: "#app",
  data: {
   chocs:[]
  },
  methods: {
 handleTileClick: function(){
    alert("test");
    },
    myClick2: function(){
    alert("test2");
    },
    myClicky: function(){
    alert("tested");
    },
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<div class="card" v-on:click="choc.subdescription==='Video'?handleTileClick():myClick2()"></div>

</div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can define a new method that accepts the subdescription and returns the function to be called. This would be used as a value for the click handler:

new Vue({
  el: "#app",
  data: () => ({
   chocs: [ 
     { subdescription: 'Video' }, 
     { subdescription: 'Poster' }, 
     { subdescription: 'Other' } 
   ]
  }),
  methods: {
    getOnClickFn: function(subdescription) {
      let fn;
      switch(subdescription) {
        case 'Video':
          fn = this.handleTileClick;
          break;
        case 'Poster':
          fn = this.myClicky;
          break;
        default:
          fn = this.myClick2;
          break;
      }
      return fn;
    },
    handleTileClick: function() { alert("test"); },
    myClick2:        function() { alert("test2"); },
    myClicky:        function() { alert("tested"); }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div 
    class="card" 
    v-for="{ subdescription } in chocs"
    :key="subdescription"
    @click="() => getOnClickFn(subdescription)()"
  >Click {{subdescription}}</div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading