Ami*_*rma 3 javascript components vue.js webpack-2 vuejs2
是否可以通过变量调用方法?我有拖放具有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>
Run Code Online (Sandbox Code Playgroud)
上面是我的示例代码,其中我在comments中提到了我的要求.我想根据拖动元素调用方法.我不知道这是可能的,但通过这种方法,我可以减少许多不需要的代码.
任何帮助将非常感谢
谢谢
在Javascript中,如果你是这样的对象:
const foo = {
bar() {},
baz() {}
};
Run Code Online (Sandbox Code Playgroud)
要"动态地"调用它,你应该输入
foo['bar']()
foo['baz']()
Run Code Online (Sandbox Code Playgroud)
所以,在你的情况下,而不是:
this.[type]()
Run Code Online (Sandbox Code Playgroud)
你应该输入:
this[type]()
Run Code Online (Sandbox Code Playgroud)
对象可以像数组索引一样进行操作,但在这种情况下,索引是字段
警告:您的$.droppable().drop功能未正确绑定.那么,此时,this不是VueJS组件:
this.在此示例中,您的drop函数必须是箭头函数才能正常工作| 归档时间: |
|
| 查看次数: |
5809 次 |
| 最近记录: |