2

nomally we predefine methods in vue.js like below.

methods : {
    func1: function(){

    } 
}

and call a function in template

<button @click="func1">click</button>

is it possible to add method dynamically in vue.js?

[for example] //actually $methods is not exist. i checked $data is exist. so it is my guess.

this.$methods["func2"] = function(){

}

in angular.js it is possible like this.

$scope["function name"] = function(){

}
1
  • Why you need this ? you can use component to add any thing dynamically. Commented Aug 11, 2018 at 7:27

1 Answer 1

6

Functions in javascript are like any other variable, so there are various ways you can dynamically add functions. A very simple solution would look like this:

<template>
  <div id="app">
    <div @click="userFuncs.myCustomFunction">Click me!</div>
  </div>
</template>

<script>
export default {
  name: "App",

  data () {
    return {
      // These contain all dynamic user functions
      userFuncs: {}
    }
  },

  created () {
    window.setTimeout(() => {
      this.$set(this.userFuncs, 'myCustomFunction', () => {
        console.log('whoohoo, it was added dynamically')
      })
    }, 2000)
  }
};
</script>

It will however give off warnings and potentially errors when the function is invoked while there is no function attached. We can get around this by having a boilerplate function that executes a default function unless a new function is defined.

We would then change the template to:

<div @click="executeDynamic('myCustomFunction')">Click me!</div>

and add the following to the component:

  methods: {
    executeDynamic (name) {
      if (this.userFuncs[name]) {
        this.userFuncs[name]()
      } else {
        console.warn(`${name} was not yet defined!`)
      }
    }
  }

You should always try to use Vue's event handlers via @someEvent or v-on:someEvent handlers, because Vue will automatically attach and detach event handlers when appropriate. In very very very rare cases something you may want to do may not be possible with Vue, you can attach event handlers yourself. Just make sure you use the beforeDestroy hook to remove them again.

Edit Vue Template

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this great answer. Can you please explain why you used window.setTimeout with a 2 sec delay in this example?
In this case it serves no other purpose than to simulate a state where no function is defined to execute. You can imagine it being an api call, or something else that calls for dynamically adding a function rather than using a computed property instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.