Zarówno magistrala odwołań, jak i magistrala zdarzeń mają problemy, gdy wpływa na renderowanie sterowania v-if
. Więc zdecydowałem się na prostszą metodę.
Pomysł polega na użyciu tablicy jako kolejki do wysyłania metod, które muszą zostać wywołane do komponentu potomnego. Po zamontowaniu komponent będzie przetwarzał tę kolejkę. Obserwuje kolejkę do wykonania nowych metod.
(Pożyczenie kodu z odpowiedzi Desmonda Lua)
Kod komponentu nadrzędnego:
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 },
})
To jest kod dla 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>
Jest dużo miejsca na ulepszenia, na przykład przejście processMethodsQueue
do miksu ...