sourcecode

vuejs 변수를 통해 동적으로 메서드 호출

copyscript 2022. 8. 15. 21:29
반응형

vuejs 변수를 통해 동적으로 메서드 호출

변수를 통해 메서드를 호출할 수 있습니까?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]()

오브젝트는 어레이인덱스처럼 조작할 수 있지만 이 경우 인덱스는 필드에 적합합니다.

경고: 고객님의$.droppable().drop함수가 올바르게 바인딩되지 않았습니다.그래서 이 시간에는this는 VueJS 컴포넌트가 아닙니다.

  • 기본적으로 vuejs 컴포넌트의 함수/기능은 es6 함수 필드(마운트된 필드 등)를 사용합니다.
  • 이 함수 내에서 화살표 기능을 사용하여 다음 항목에 대한 오른쪽 컨텍스트를 키핑합니다.this이 예에서는,drop올바르게 작동하려면 기능이 화살표 함수여야 합니다.

내가 그 기능을 다이나믹하게 넘겼다고 생각하겠지

함수 이름을 "save Record"로 전달합니다.

이렇게 해봐.저는 잘 동작합니다. :)

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

언급URL : https://stackoverflow.com/questions/48284354/calling-method-dynamically-through-variables-in-vuejs

반응형