我對 Vue JS 比較陌生,但感覺我對組件層次結構有比較好的掌握。只是在這里遇到一個問題,我對此感到有些困惑,并且與我對應該做什么的理解不符props。
在我的父組件中,我有一個data名為的屬性loading,它被初始化為true. 我還有一個名為 的屬性dataItems,它被初始化為null但由呼叫 API 的異步方法填充。在dataItems成功填充的點上,loading也應設定為 false。這個 API 呼叫是在mounted函式內部進行的。
一切作業為在父級別預期,但通過這兩個屬性下降到(通過道具)的子組件似乎只(傳下去其初始狀態true,并null分別),并從不對其進行更新。
作為一個簡單的例子,我<p>在父組件和子組件中添加了一些標簽作為輸出資料的一種方式,這是我使用的速記 HTML 和 JS。
父組件:
<template>
<p>Loading: {{loading}}</p> // outputs Loading: false
<p>dataItems: {{dataItems}}</p> //outputs JSON string
<ChildComponent :loading="loading" :dataItems="dataItems" />
</template>
<script>
data: function() {
loading: true
dataItems: null
},
methods: {
getDataItems: async function() {
//.. make API call
this.dataItems = response.data
loading = false
}
},
mounted: function() {
this.getDataItems()
}
</script>
子組件:
<template>
<p>Loading: {{loading}}</p> // outputs Loading: true
<p>dataItems: {{dataItems}}</p> //no output
</template>
<script>
props: ["loading", "dataItems"],
data: function() {
loading: this.loading
dataItems: this.dataItems
},
</script>
所以當父組件和子組件一起渲染時,我看到的是:
Loading: false // from parent
dataItems: {"someJsonString"} // from parent
Loading: true // from child
//from child
我不明白為什么傳遞下來的資料沒有被更新,因為我有點理解這是 Vue.js 的重點。就像我說的,我對這個框架比較陌生,所以我有可能犯了一個簡單的錯誤。
如果有人能給我一個正確方向的觀點,我將不勝感激!
謝謝
uj5u.com熱心網友回復:
您的代碼是正確的,但您決定實施的方法似乎props不適用于這種情況。
你(正如你提到的)用道具初始化你的孩子狀態(它的資料)。當您需要從子組件更改此資料時,此方法很有用,因為您不能直接從子組件更改 prop,只有父組件可以。
現在,我看到您的 Child 組件的目的只是顯示父級發送的資訊(通過 props)。因此,您可以直接從模板訪問作為refs的 props 值(它們是反應性的)。
子組件訪問模板中的道具:
<template>
<p>Loading: {{ loading }}</p>
<p>dataItems: {{ dataItems }}</p>
</template>
<script>
props: ["loading", "dataItems"],
data: function() {
// Use the props directly in your template
},
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377015.html
