[英]How do I loop through an array in an external JS file using VueJS CDN?
我創建了一個通過 CDN 使用 VueJs 的頁面,並試圖弄清楚如何從外部 JS 文件中循環數組中的數據。 我嘗試如下導入數據,但在控制台中出現未定義的錯誤。
我的 index.html 中的循環如下;
<ul>
<li v-for="animal in animals">
{{ animal.type }}
</li>
</ul>
那么這個索引末尾的JS.html如下;
<script src="js/list.js"></script>
var app = new Vue({
router: router,
el: '#app',
data() {
return {
animals: animals
};
}
});
我的包含數組的外部 JS 文件稱為 list.js;
export animals [
{
type: 'Cat'
},
{
Type: 'Dog'
}
];
這實際上與 vue 沒有太大關系,而是您如何嘗試引入數據。
如果要使用腳本標簽,動物的導出將不起作用。
如果這只是開始,在 list.js 中,你可以這樣做
var animals = [ ... your data ];
或者,如果您想使用 export....
將您的導出更改為
export const animals = [
{
type: 'Cat'
},
{
Type: 'Dog'
}
];
<html lang="en"> <head> <meta charset="UTF-8" /> <div id="testapp"> <ul> <li v-for="animal in animals"> {{ animal.type }} </li> </ul> </div> </head> <body> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script type="module"> import {animals} from "/scripts/list.js" var app = new Vue({ el: '#testapp', data() { return { animals: animals }; } }); </script> </body> </html>
在您的 list.js 文件中,您必須像這樣導出為 const。
export const animals = [
{
type: 'Cat'
},
{
Type: 'Dog'
}
]
並像這樣導入它(在 your.js 文件中):
import { animals } from 'js/list.js'
var app = new Vue({
router: router,
el: '#app',
data() {
return {
animals: animals //you can use animal in data like this
};
}
});
之后,您可以隨意循環,...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.