Is it possible to set dynamic on event in VueJS? I try to build a dynamic form as component with inputs that can listen on everything. Here an example:
JavaScript
x
25
25
1
import Vue from 'vue';
2
3
let formItems = {
4
{type: 'checkbox', id: 'some-id', on:'change', model: 'someId'},
5
{type: 'url', id: 'another-id', on:'keyup', model:'anotherId'},
6
};
7
8
let params = {
9
someId: true,
10
anotherId: 'http://www.example.com',
11
};
12
13
new Vue({
14
el: '#app',
15
data: {
16
formItems: formItems,
17
params: params,
18
},
19
methods: {
20
checkInputParams(e) {
21
e.preventDefault();
22
// Do some stuff.
23
}
24
}
25
});
JavaScript
1
22
22
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
2
3
<div id="app">
4
<div class="form-group" v-for="item in formItems">
5
<input type="checkbox" <!-- Also need a workaround for dynamic type and v-model -->
6
:id="item.id"
7
:class="(item.class ? item.class : '')"
8
:title="(item.title ? item.title : '')"
9
:placeholder="(item.placeholder ? item.placeholder : '')"
10
:autocomplete="(item.autocomplete ? item.autocomplete : false)"
11
:disabled="(item.disabled ? item.disabled : false)"
12
:max="(item.max ? item.max : '')"
13
:min="(item.min ? item.min : '')"
14
:maxlength="(item.maxLength ? item.maxLength : '')"
15
:multiple="(item.multiple ? item.multiple : '')"
16
:name="(item.name ? item.name : '')"
17
:readonly="(item.readonly ? item.readonly : false)"
18
:required="(item.required ? item.required : false)"
19
v-on="{{ item.on }}:checkInputParams" <!-- Here I try the dynamic v-on -->
20
v-model="params[item.model]"/>
21
</div>
22
</div>
Is it possible to set a dynamic v-on event like v-on="<variable>:<function>"
?
Advertisement
Answer
From Vue 2.4.0+, v-on
accepts an object syntax
Refer this documentation
JavaScript
1
1
1