![](/img/trans.png)
[英]My child component checkbox is not updating when props changed from the parent?
[英]child component not updating when prop (boolean) is changed by parent component
當我更改父 Vue 組件中的 props 值(布爾值)時,子組件不會更新以觸發模態打開。
在我的父組件中,單擊事件將 openModal 的值從 false 設置為 true。 然后這個值通過一個 prop 向下傳遞到一個子組件。 在該子組件中,更新后的布爾值應該通過類綁定將一個類添加到一個 div,作為回報,它會打開一個模態。
父組件:
<FilmListItem
v-for="slice in slices"
@click.native="openModal=true"
/>
<child-component :modal="openModal">
...
data() {
return {
openModal: false
}
}
子組件:
<div
class="modal__container"
:class="{ 'modal--show': showModal }">
...
export default {
props: {
modal: Boolean
},
data() {
return {
showModal: this.modal
}
In the vue dev tools I can see, that the value of the prop changes in the parent. Yet, my child component doesn't update. It worked when I forced the child component to reload when I was assigning a new :key value together with changing the Boolean. But that feels a little hacky to me. Also, a watcher within the child component didn't do the trick. It simply wouldn't watch the changed prop value. Any ideas very much appreciated. Thanks in advance.
我實際上現在自己找到了解決方案:
在子組件中,我試圖通過數據對象訪問props的數據。 但我只是直接訪問道具的數據:
<div
:class="{ 'modal--show': modal }">
...
export default {
props: {
modal: Boolean
}
}
正確的。
如果此父/子關系更復雜,或者您需要向上傳遞回父級,則其他同步選項:
將 :modal 值放在 Vuex 存儲中,並在子組件上使用計算屬性。
使用 EventBus: https ://alligator.io/vuejs/global-event-bus/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.