是否可以在VueJS中设置动态事件?我尝试构建一个动态表单 作为具有可以监听所有内容的输入的组件。这是一个例子:
microtime()

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.
}
}
});

是否可以设置动态v-on事件,例如<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>
?
答案 0 :(得分:6)
从Vue 2.4.0 +,v-on
接受对象语法
<button v-on="{ mousedown: doThis, mouseup: doThat }"></button>
答案 1 :(得分:0)
尝试:
<button v-on="buttonListners"></button>
{
data: () => { remoute: { "mousedown": "doThis" } }
computed: {
buttonListners() {
return Object.entries(this.remoute).reduce((acc, [eventName, methodName]) => {
acc[eventName] = this[methodName];
return acc;
}, {})
}
}
}