簡體   English   中英

Vue.js中嵌套對象的訪問屬性

[英]Access property of nested object in Vue.js

晚上好,

我有一段代碼可以生成對象的javascript數組(標頭),其中的對象也包含數組(我已經為您將其轉換為JSON字符串):

[  
   {  
      "text":"One",
      "link":"#one",
      "subheaders":[  
         {  
            "text":"Installation",
            "link":"#Installation"
         }
      ]
   },
   {  
      "text":"Two",
      "link":"#two",
      "subheaders":[  
         {  
            "text":"Installation2",
            "link":"#Installation2"
         }
      ]
   }
]

我正在嘗試使用以下方法訪問它:

<ul>
    <li v-for="header in headers">
        <a :href="header.link">{{ header.text }}</a>
    </li>
    <ul>
        <li v-for="subheader in header.subheaders">
            <a :href="subheader.link">{{ subheader.text }}</a>
        </li>
    </ul>
</ul>

問題在於第二個循環,我不斷得到:

[Vue警告]:屬性或方法“標頭”未在實例上定義,但在渲染期間被引用。

刪除第二個循環后,似乎就消失了。

您的第二個循環不在第一個循環的范圍內。 我想你想要這樣的東西:

<ul>
    <li v-for="header in headers">
        <a :href="header.link">{{ header.text }}</a>
        <ul>
            <li v-for="subheader in header.subheaders">
                <a :href="subheader.link">{{ subheader.text }}</a>
            </li>
        </ul>
    </li>
</ul>

為了更好的想象,vue-js做這樣的事情(不准確):

for (header in headers) {
  echo '<li><a>' + header.text + '</a></li>'
}

另一個解決方案:

<ul>
<template v-for="header in headers">
    <li>
        <a :href="header.link">{{ header.text }}</a>
    </li>
    <ul>
        <li v-for="subheader in header.subheaders">
            <a :href="subheader.link">{{ subheader.text }}</a>
        </li>
    </ul>
</template>
</ul>

但是最好將子<ul>放在<li> ,就像在puelo的代碼中一樣

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM