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監(jiān)聽(tīng)的事件是 父組件傳遞過(guò)來(lái)的,而不是在這里寫(xiě)死為click,我該怎么寫(xiě)?
我當(dāng)然知道使用props傳遞,我想知道v-on后面該怎么寫(xiě)。如果直接寫(xiě)propname的話vue會(huì)認(rèn)為要監(jiān)聽(tīng)的事件是propname,而不是具體的事件。
題主的需求比較特殊,如果是這樣的話可能只能使用render
代替template
了:
<p id="app">
<button-counter :event="'click'">abc</button-counter>
</p>
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,
},
})
父組件傳參給字組件都是通過(guò)props的,props可以是function,所以你可以傳一個(gè)function給字組件