Reputation: 47
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(){
}
Upvotes: 2
Views: 3299
Reputation: 20737
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.
Upvotes: 6