Reputation: 143
data() {
return {
arrayToBeSorted: [1, 2, 3, 4, 5, 6, 7, 8],
isManipulatingArray: false,
shuffleButtonText: "Shuffle!",
sortAlgorithms: [
{ id: 1, name: "Bubble sort", fn: bubbleSort },
{ id: 2, name: "Selection sort", fn: selectionSort },
{ id: 3, name: "Insertion sort", fn: insertionSort },
],
}
},
methods: {
sort: function (Algorithm) {
this.Algorithm.fn();
},
show: function() {
console.log("shuffle!");
},
bubbleSort: function() {
console.log("bubble!");
},
selectionSort: function() {
console.log("selection!");
},
insertionSort: function() {
console.log("insertion!");
},
}
<div class="buttons-container">
<button class="button" v-for="Algorithm in sortAlgorithms" :key="Algorithm.id" v-on:click="Algorithm.fn">{{ Algorithm.name }}</button>
</div>
When I hit the button I want the respective method to be invoked via the sort function but I'm getting an error of function not defined.
Upvotes: 0
Views: 410
Reputation: 20039
Try using this
context
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
new Vue({
el: '#app',
data() {
return {
arrayToBeSorted: [1, 2, 3, 4, 5, 6, 7, 8],
isManipulatingArray: false,
shuffleButtonText: "Shuffle!",
sortAlgorithms: [{
id: 1,
name: "Bubble sort",
fn: this.bubbleSort
},
{
id: 2,
name: "Selection sort",
fn: this.selectionSort
},
{
id: 3,
name: "Insertion sort",
fn: this.insertionSort
},
],
}
},
methods: {
sort: function(Algorithm) {
Algorithm.fn();
},
show: function() {
console.log("shuffle!");
},
bubbleSort: function() {
console.log("bubble!");
},
selectionSort: function() {
console.log("selection!");
},
insertionSort: function() {
console.log("insertion!");
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="buttons-container">
<button class="button" v-for="Algorithm in sortAlgorithms" :key="Algorithm.id" v-on:click="Algorithm.fn">{{ Algorithm.name }}</button>
</div>
</div>
Upvotes: 1