0

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.

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.