Implementing dynamic method calls using variables in Vue.js

Can methods be called through variables? I have drag and drop elements with IDs, and based on the ID, I need to call a specific method. For example:

<template>
   <div>
    <div id="draggable">
      <div class="draggable" id="db">Step2</div>
      <div class="draggable" id="spstep"> Step</div>
      <div class="draggable" id="merge">Merge</div>
      <div class="draggable" id="copy">copy</div>
    </div>
     <div id="id="draggable"">Drop Here</div>
   </div>
 </template> 

<script>
  export default {

  data () {

   }
  mounted () {
  var _this = this
  $(".draggable").draggable({
     grid: [ 20, 20 ],
     appendTo: '#droppable',
     // containment: "window",
     cursor: 'move',
     revertDuration: 100,
     revert: 'invalid',
     helper: 'clone',
     refreshPositions: true,
     scroll: true,
     containment: "document",
      zIndex: 10000,
 });

 $("#droppable").droppable({
     accept: ".draggable",
     tolerance: "intersect",
     drop: function (event, ui) {         
       var leftPosition  = pos.left;//ui.offset.left - $(this).offset().left;
       var topPosition   = pos.top;//ui.offset.top - $(this).offset().top;
       console.log(leftPosition + "  "+ topPosition);
       var type = ui.draggable.attr("id");

       
       if(type == 'db')
          _this.db()

       if(type == 'spstep')
          _this.spstep()

       if(type == 'merge')
          _this.merge()

       if(type == 'copy')
          _this.copy()   
        
        // _this.[type]() // Syntax error  

       }
     }); 
 }
 methods: {
  db(){
    //do something for db
  }
  spstep(){
    //do something for spstep
  }
  merge(){
    //do something for merge
  }
  copy(){
    //do something for copy
  }
}
</script>
<style>
</style>

In the provided sample code, the desired functionality is outlined in the comments. It aims to call methods based on the dragged element's ID. While the exact implementation might not be correct, it serves as a way to streamline the code effectively.

Any assistance or advice on improving this approach would be greatly appreciated.
Thank you

Answer №1

When working with JavaScript and dealing with objects, you can define them like so:

const foo = {
    bar() {},
    baz() {}
};

To dynamically call these methods, you would use:

foo['bar']()
foo['baz']()

So instead of writing:

this.[type]()

You should write:

this[type]()

An object in JavaScript can be manipulated like an array index, but in this case, the indexes are simply the fields.

Warning: Your $.droppable().drop function is not properly binded. Therefore, at this point, 'this' does not refer to the VueJS component:

  • In the basic functions/methods of your VueJS component, utilize ES6 arrow functions for proper context handling (such as in your mounted method).
  • Within these functions, use arrow functions to maintain the correct context for 'this'. For example, your drop function must be an arrow function to function correctly.

Answer №2

When approaching this scenario, keep in mind that the function should be passed as a dynamic value.

In my case, I passed the function name as "saveRecord".

To implement this successfully, try using the following method. It has proven effective for me :)

var mydynamic_Function_Name = "saveRecord";
this[mydynamic_Function_Name]();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it more advantageous in Vue to pre-process and save data directly to the data property, or to utilize computed properties?

I am interested in hearing diverse perspectives on this topic. When working with Vue (and possibly other frameworks), is it more beneficial to prepare non-reactive data through a method and store it in the data for use in the template, or is it preferable ...

Why is it that when drawing rectangles with HTML 5 canvas using pixel size, a black rectangle appears instead of blue?

My intention was to create a large blue rectangle measuring 320 X 240 pixels on the Canvas in Firefox, but I'm only getting a black rectangle instead. This issue is perplexing as I am simply experimenting with pixel drawing and for some reason, it&apo ...

Creating draggable elements with inner content using jQuery UI is a fantastic way to enhance user interaction

Take a look at the image below. We want to know: when a draggable element is moving, how can we compare its inner elements and check 8 side points along the same line, then draw a line between these two points? I am using jQuery UI and jQuery 1.8. Can y ...

Creating a conditional property in TypeScript based on an existing type - a comprehensive guide

Imagine if I had the following: type Link = { text: string; link: string; } interface BigLink extends Link { some: number; something: string; else: string; } However, there's a variable that shares all these properties except for the fact ...

Next.js 11 Script integration for TruConversion Heatmap Tracking

I'm in the process of setting up TruConversion's heatmap script on my Next.js 11 website. According to TruConversion's website, the script should be added before the closing </head> tag. However, Next.js documentation advises against ...

Execute one observable at a time in Angular

In my data, I have an array of objects with the following details: [ { "name":"Uber", "points":20, "nodeName":"C=GB,L=London,O=Uber", "port":10007, "nodeType":"merchant" }, { "name":"Starbucks", ...

Using Laravel and VueJS to send an array to the controller using Axios

I've developed a Laravel 5.4 application combined with VueJS 2.0 for the frontend. The issue I'm facing is that after populating the visitors array on the page and trying to post it to the controller, the data seems to disappear upon returning f ...

"The controller's $scope isn't being updated within the DIV following a routing change

My website contains ng-view partials that change based on routing updates in $routeProvider. anmSite.config(function($routeProvider, $locationProvider){ $locationProvider.html5Mode(true); $routeProvider //Home page route .when("/", { temp ...

Having trouble getting the node serialport module to function properly when using the child process fork()

My current project involves implementing an asynchronous read in USB using fork() from the child_process module in electron. Essentially, upon clicking a div (id="read"), a message is sent from the renderer process to the main process. The main process the ...

Why is it that when I integrate secure-ls with vuex-persistedstate, the stored Vuex data no longer retains the session data?

Before setting up secure-ls as shown here: https://codesandbox.io/s/7l9wb my localStorage under the 'vuex' key looked something like this: {authUser:{name:'My name', authenticated: true}} After configuring secure-sl in vuex-persisteds ...

Retrieving the input[text] value in TypeScript before trimming any special characters

One of the tasks I am working on involves a form where users can input text that may contain special characters such as \n, \t, and so on. My objective is to replace these special characters and then update the value of the input field accordingl ...

Clicking on the Jquery datepicker beforeShowDay remains possible despite all days being set as not selectable

https://i.sstatic.net/P3mII.png I've been using jQuery UI for datepicker and I'm attempting to disable certain dates. I read that this can be done using beforeShowDay when initializing the datepicker, but I'm having trouble getting it to wo ...

The Facebook app is experiencing issues on Chrome, yet is functioning properly on Firefox

Lately, I've ventured into the world of creating Facebook Apps on heroku. After creating a test app and uploading a page with HTML5, CSS, and Javascript, I encountered an issue where the app wasn't displaying correctly in Google Chrome , but work ...

Encountering an error while trying to install the VUE CLI using the npm command with the message "

I'm currently using PC/Windows 10 with Node.js version 15.0.0 and npm 6.14.8. While trying to set up Vue CLI, I encountered an error message. Despite having the latest Node.js version installed, my attempts to resolve the issue by running commands l ...

Tips to prevent redundancy in a one-line 'if' statement in JavaScript

While working on a piece of code, I came across something bothersome and couldn't find a solution even after doing some research. It's functional, but it feels redundant to have to type this.className three times: this.className != 'selecte ...

Whenever I click on a button, I want to modify the background color of my react-modal

Having an array of images with clickable overlays and a modal that changes the background color based on the overlay name when clicked is the goal. However, passing this value as a prop proves challenging since the images are generated through a function a ...

Discover the step-by-step process of leveraging require.js to define a template similar to a Vue component and establish a

When working on projects that involve express and require.js along with Vue CDN, I often encounter the need to define a template using require.js that is similar to Vue components. In my index.js file, I have a data list that I want to display in the inde ...

Incorporate Current and Total Slide Counters into Your Bootstrap 5 Carousel

How can I incorporate slide numbering into this Bootstrap 5 carousel example? I want to display the current slide number and the total number of slides in the carousel. The slide counters can be found in the carousel-pager div, where pager-current repres ...

Customize a div's background color with an Angular directive

Imagine having a div element: <div id="wrapper"> some text </div> How can you create an angular directive that changes the background based on user input? For instance, you might have tried: <div id="wrapper" color temperature="51"> ...

Retrieve JSON information from a document through JavaScript

Is it possible to fetch JSON data using JavaScript without relying on jQuery? I am only interested in retrieving data using pure JavaScript. Here is an example of my JSON file: {"JsonProjectIDResult":[{"_capacity":15,"_description":"Meeting Room","_dev_d ...