以编程方式为 VueJS 中的动态组件绑定自定义事件
Posted
技术标签:
【中文标题】以编程方式为 VueJS 中的动态组件绑定自定义事件【英文标题】:Programmatically bind custom events for dynamic components in VueJS 【发布时间】:2018-06-23 08:47:31 【问题描述】:在我的 vuejs 应用程序中,我通过以下方式使用动态组件:
<mycomponent>
<component ref="compRef" :is="myComponent" v-bind="myComponentProps"></component>
<div class="my-buttons">
<my-button label="Reset" @click="reset()"/>
</div>
</mycomponent >
myComponent
是父组件上的一个 prop,它包含要注入的实际组件。
myComponentProps
也是 props,用于保存注入实例的 porps。
我想知道如何将侦听器动态绑定到组件 - 我知道I cannot 将一个对象发送到具有多个事件的 v-on。
我正在考虑以编程方式添加它,但没有找到任何关于如何为 Vue 自定义事件完成它的信息(类似于 addEventListener
的自定义事件)
任何提示将不胜感激!
【问题讨论】:
您可以将多个处理程序附加到具有 Vue 2.4+ 的对象的事件(请参阅您链接的线程中的最后一条评论)。 vuejs.org/v2/api/#v-on 【参考方案1】:使用 Vue 2.2+,您可以使用 $on(eventName, callback)
以编程方式添加事件侦听器:
new Vue(
el: '#app',
created()
const EVENTS = [
name: 'my-event1', callback: () => console.log('event1'),
name: 'my-event2', callback: () => console.log('event2'),
name: 'my-event3', callback: () => console.log('event3')
]
for (let e of EVENTS)
this.$on(e.name, e.callback); // Add event listeners
// You can also bind multiple events to one callback
this.$on(['click', 'keyup'], e => console.log('event', e) )
)
<script src="https://unpkg.com/vue@2.6.8/dist/vue.min.js"></script>
<div id="app">
<div>
<!-- v-on:EVENTNAME adds a listener for the event -->
<button v-on:click="$emit('my-event1')">Raise event1</button>
<button v-on:click="$emit('my-event2')">Raise event2</button>
<button v-on:click="$emit('my-event3')">Raise event3</button>
</div>
<div>
<!-- v-on shorthand: @EVENTNAME -->
<button @click="$emit('my-event1')">Raise event1</button>
<button @click="$emit('my-event2')">Raise event2</button>
<button @click="$emit('my-event3')">Raise event3</button>
</div>
</div>
使用 Vue 2.6+,您可以在模板中add an event listener dynamically:
new Vue(
el: '#app',
data:
eventname: 'click',
,
methods:
handler(e)
console.log('click', e.target.innerText)
)
<script src="https://unpkg.com/vue@2.6.8/dist/vue.min.js"></script>
<div id="app">
<button @[eventname]="handler">Raise dynamic event</button>
<!-- Set dynamic key to null to remove event listener -->
<button @click="eventname = null">Unbind event</button>
</div>
您还可以使用v-on="event1: callback, event2: callback, ..."
声明性地绑定多个事件侦听器:
new Vue(
el: '#app',
methods:
onClick() console.log('click') ,
onKeyUp(e) console.log('keyup', e.keyCode)
)
<script src="https://unpkg.com/vue@2.6.8/dist/vue.min.js"></script>
<div id="app">
<input type="text" placeholder="type here" v-on="click: onClick, keyup: onKeyUp">
</div>
【讨论】:
以上是关于以编程方式为 VueJS 中的动态组件绑定自定义事件的主要内容,如果未能解决你的问题,请参考以下文章
vuejs的组件化开发中,要怎么自定义class,覆盖原有的css样式