Xe buýt tham chiếu và sự kiện đều có vấn đề khi kết xuất điều khiển của bạn bị ảnh hưởng v-if. Vì vậy, tôi quyết định chọn một phương pháp đơn giản hơn.
Ý tưởng là sử dụng một mảng làm hàng đợi để gửi các phương thức cần được gọi đến thành phần con. Khi thành phần được gắn kết, nó sẽ xử lý hàng đợi này. Nó theo dõi hàng đợi để thực thi các phương thức mới.
(Mượn một số mã từ câu trả lời của Desmond Lua)
Mã thành phần chính:
import ChildComponent from './components/ChildComponent'
new Vue({
el: '#app',
data: {
item: {},
childMethodsQueue: [],
},
template: `
<div>
<ChildComponent :item="item" :methods-queue="childMethodsQueue" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.childMethodsQueue.push({name: ChildComponent.methods.save.name, params: {}})
}
},
components: { ChildComponent },
})
Đây là mã cho ChildComponent
<template>
...
</template>
<script>
export default {
name: 'ChildComponent',
props: {
methodsQueue: { type: Array },
},
watch: {
methodsQueue: function () {
this.processMethodsQueue()
},
},
mounted() {
this.processMethodsQueue()
},
methods: {
save() {
console.log("Child saved...")
},
processMethodsQueue() {
if (!this.methodsQueue) return
let len = this.methodsQueue.length
for (let i = 0; i < len; i++) {
let method = this.methodsQueue.shift()
this[method.name](method.params)
}
},
},
}
</script>
Và có rất nhiều chỗ để cải thiện như chuyển processMethodsQueuesang mixin ...