javascript - vue如何根据配置监听的事件类型?
本文介绍了javascript - vue如何根据配置监听的事件类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
Vue.component('button-counter', {
template: '<button v-on:click="increment()">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
increment: function () {
this.counter += 1
}
},
})
比如上面的组件,我希望 v-on监听的事件是 父组件传递过来的,而不是在这里写死为click,我该怎么写?
我当然知道使用props传递,我想知道v-on后面该怎么写。如果直接写propname的话vue会认为要监听的事件是propname,而不是具体的事件。
解决方案
题主的需求比较特殊,如果是这样的话可能只能使用render
代替template
了:
<div id="app">
<button-counter :event="'click'">abc</button-counter>
</div>
const counter = Vue.component('button-counter', {
render(createElement) {
return createElement(
'button', {
on: {
[this.event]: this.increment,
},
},
`${this.counter}`,
)
},
data() {
return {
counter: 0,
}
},
props: {
event: String
},
methods: {
increment() {
this.counter += 1
},
},
})
new Vue({
el: '#app',
components: {
'button-counter': counter,
},
})
这篇关于javascript - vue如何根据配置监听的事件类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文