白豬掌柜的
2018-11-24 14:18:32
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,而不是具體的事件。
1 回答

RISEBY
TA貢獻1856條經驗 獲得超5個贊
題主的需求比較特殊,如果是這樣的話可能只能使用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,
},
})
添加回答
舉報
0/150
提交
取消