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:
import Vue from 'vue'; let formItems = { {type: 'checkbox', id: 'some-id', on:'change', model: 'someId'}, {type: 'url', id: 'another-id', on:'keyup', model:'anotherId'}, }; let params = { someId: true, anotherId: 'http://www.example.com', }; new Vue({ el: '#app', data: { formItems: formItems, params: params, }, methods: { checkInputParams(e) { e.preventDefault(); // Do some stuff. } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script> <div id="app"> <div class="form-group" v-for="item in formItems"> <input type="checkbox" <!-- Also need a workaround for dynamic type and v-model --> :id="item.id" :class="(item.class ? item.class : '')" :title="(item.title ? item.title : '')" :placeholder="(item.placeholder ? item.placeholder : '')" :autocomplete="(item.autocomplete ? item.autocomplete : false)" :disabled="(item.disabled ? item.disabled : false)" :max="(item.max ? item.max : '')" :min="(item.min ? item.min : '')" :maxlength="(item.maxLength ? item.maxLength : '')" :multiple="(item.multiple ? item.multiple : '')" :name="(item.name ? item.name : '')" :readonly="(item.readonly ? item.readonly : false)" :required="(item.required ? item.required : false)" v-on="{{ item.on }}:checkInputParams" <!-- Here I try the dynamic v-on --> v-model="params[item.model]"/> </div> </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