在我的vuejs应用程序中,我使用动态组件,方法如下:
<mycomponent>
<component ref="compRef" :is="myComponent" v-bind="myComponentProps"></component>
<div class="my-buttons">
<my-button label="Reset" @click="reset()"/>
</div>
</mycomponent >
Run Code Online (Sandbox Code Playgroud)
myComponent
是父组件的prop,它包含要注入的实际组件.
myComponentProps
也是支撑注入实例的porps的prop.
我想知道如何动态地将侦听器绑定到组件 - 我知道我不能将对象发送到具有多个事件的v-on.
我正在考虑以编程方式添加它,但是没有找到任何有关如何为Vue自定义事件完成的信息(类似于自定义事件的类型addEventListener
)
任何提示将不胜感激!
ton*_*y19 39
使用Vue 2.2.0+,您可以通过编程方式添加事件监听器$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) })
}
})
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
您还可以声明性地绑定多个事件侦听器v-on="{event1: callback, event2: callback, ...}"
:
new Vue({
el: '#app',
data: {
eventname: 'click',
},
methods: {
handler(e) {
console.log('click', e.target.innerText)
}
}
})
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13463 次 |
最近记录: |