可以通过变量调用该方法吗?我有ID的拖放元素,根据ID我必须调用该方法.

<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");

       //Here call methods according to id of draggable element
       //like 
       //current implement which is not enhanced code
       if(type == 'db')
          _this.db()

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

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

       if(type == 'copy')
          _this.copy()   
        //desired implementation alike
        _this.[type]() // this syntax is wrong and throws an error  
       }
     }); 
 }
 methods: {
  db(){
    //db called do something
  }
  spstep(){
    //spstep called do something
  }
  merge(){
    //merge called do something
  }
  copy(){
    //copy called do something
  }
}
</script>
<style>
</style>

以上是我的示例代码,我在注释中提到了我的需求.我想根据拖拽的元素调用这些方法.我甚至不知道这是可能的,但通过这种方法,我可以减少很多不需要的代码.

任何帮助都将不胜感激

推荐答案

在Javascript中,如果您是这样的对象:

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

要称之为"动态",您应该键入

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

因此,在你的情况下,不是:

this.[type]()

你应该输入:

this[type]()

对象可以像数组索引一样进行操作,但在本例中,索引只是字段

Warning:您的$.droppable().drop函数没有正确绑定.因此,此时,this不是VueJS组件:

  • 在vuejs组件的基本函数/方法中,使用es6函数字段(如挂载的…).
  • 在这个函数中,使用arrow函数为this设置正确的上下文.在本例中,drop函数必须是箭头函数才能正常工作

Vue.js相关问答推荐

过渡如何在 Vue JS 3 中的图像上工作?

vuejs3 youtube-plugin YT 未定义控制台错误

vue3 ssr 不返回纯 html

在 vue.js 中添加新类时样式不适用

在重复表行中

如何在 vue 组件中定义变量? (Vue.JS 2)

在 Vuex Store 模块中使用 Vue.js 插件

v-for 内部的组件

如何在 vue 3 脚本设置中使用

Transition-group children must be keyed...but they are keyed

Vue 和 TypeScript 所需的props

vuetify:以编程方式显示对话框

取消选中单选按钮

如何从 vue 组件调用 App.vue 中的方法

Vuex:无法读取未定义的属性'$store'

在 VUE JS 的光标位置插入字符

将登录页面包含在单页应用程序中是否不安全?

$set 不是函数

vue 未在实例上定义,但在渲染期间引用

表格行上的 Vuejs 转换