Ref และเหตุการณ์รถบัสทั้งสองมีปัญหาเมื่อการควบคุมของคุณ Render v-if
รับผลกระทบจาก ดังนั้นฉันจึงตัดสินใจเลือกวิธีที่ง่ายกว่านี้
แนวคิดนี้ใช้อาร์เรย์เป็นคิวเพื่อส่งเมธอดที่ต้องการเรียกไปยังคอมโพเนนต์ลูก เมื่อติดตั้งคอมโพเนนต์แล้วจะประมวลผลคิวนี้ มันเฝ้าดูคิวเพื่อดำเนินการวิธีการใหม่
(ยืมรหัสจากคำตอบของ Desmond Lua)
รหัสองค์ประกอบหลัก:
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 },
})
นี่คือรหัสสำหรับ 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>
และมีพื้นที่ให้ปรับปรุงอีกมากเช่นย้ายprocessMethodsQueue
ไปมิกซ์อิน ...