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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>