calling method dynamically through variables in vuejs

14,685

Solution 1

In Javascript if you are an object like this :

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

To call this "dynamicly" you should type

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

So, in your case, instead of :

this.[type]()

You should type :

this[type]()

Object could be manipulated like array index but, in this case, indexes are juste the fields

Warning : Your $.droppable().drop function is not correctly binded. So, at this time, the this is not the VueJS component :

  • in basics functions/methods of your vuejs component use the es6 functions fields (like your mounted, ...).
  • Inside this functions, use arrow function to kepp the right context for this. In this example, your drop function must be an arrow function to work correctly

Solution 2

you just think i pass the function as a dynamic.

I pass the function name as a "saveRecord".

try this way. It works well for me :)

var mydynamic_Function_Name = "saveRecord";
this[mydynamic_Function_Name]();
Share:
14,685

Related videos on Youtube

Amit Sharma
Author by

Amit Sharma

Updated on June 18, 2022

Comments

  • Amit Sharma
    Amit Sharma almost 2 years

    Is it possible to call the method through variables? I have drag and drop elements having ID and according to id I have to call the method. Consider the following Eg.

    <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>
    

    Above is my sample code in which I have mentioned my requirements in comments.I want to call the methods according to dragged element. I don't know even this is possible but by this approach, I can reduce lots of unwanted code.

    Any help would be highly appreciated
    Thanks

  • Amit Sharma
    Amit Sharma over 6 years
    it throws error "TypeError: this[type] is not a function", Also I want to implement in vuejs.
  • Roy J
    Roy J over 6 years
    What is the value of type when it throws that error?
  • Amit Sharma
    Amit Sharma over 6 years
    @RoyJ, a string "db", "spstep" as mentioned on draggable element
  • Roy J
    Roy J over 6 years
    And what is this at that point? I suspect it's not your component. You may want do var self = this; in your mounted and use self inside the jQuery setups.
  • throrin19
    throrin19 over 6 years
    seft = this is really bad. Use the arrow functions instead of : - in basics functions/methods of your vuejs component use the es6 functions fields (like your mounted, ...). - Inside this functions, use arrow function to kepp the right context for this. In this example, your drop function must be an arrow function to work correctly
  • Amit Sharma
    Amit Sharma over 6 years
    @RoyJ, "this" is the instance of component, so to access the method we do like this.db(), or this.spstep() and so on, so basically its way to call the methods in vuejs
  • Amit Sharma
    Amit Sharma over 6 years
    @RoyJ, As per your suggestion I am using "_this" for vuejs "this" so that its can be differentiated with jquery "this"
  • Roy J
    Roy J over 6 years
    @AmitSharma You still have the . in _this.[type](). You need to remove the ..
  • throrin19
    throrin19 over 6 years
    @AmitSharma I recommand you to use the arrow function or the .bind(this) instead of copy of this
  • Milan Maharjan
    Milan Maharjan over 5 years
    @throrin19 How do i pass the parameter in the method ?
  • throrin19
    throrin19 over 5 years
    @milan-maharjan exactly the same with other function this[type](param1, param2)
  • Miroslav
    Miroslav over 3 years
    I tried this[get${type}FieldValue](this.action, this.field.id) but I get an error "not a function".
  • Miroslav
    Miroslav over 3 years
    Same for this <template v-if="[get${type}FieldValue](action, field.id) !== undefined"> in VueJS