Appearance
Vue.js
常规做法是使用框架如 Nuxt.js ,非常规做法是 HTML 直接引用 Vue.js 。
安装 Nginx 。
切换到站点文件夹。
新建文件 books.json 。
[
{
"id": 1,
"name": "西游记"
},
{
"id": 2,
"name": "水浒传"
},
{
"id": 3,
"name": "三国演义"
},
{
"id": 4,
"name": "红楼梦"
}
]新建文件 books-vue-1.html 。
<html>
<head>
<meta charset="utf-8" />
<title>图书</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<ul>
<li v-for="record in records" :key="record.id">{{ record.name }}</li>
</ul>
</div>
<script>
const app = Vue.createApp({
data() {
return {
records: []
}
},
mounted() {
fetch('/books.json')
.then(response => response.json())
.catch(error => {
console.error(error);
})
.then(records => {
if (records) {
this.records = records;
}
});
}
});
app.mount('#app');
</script>
</body>
</html>访问 http://localhost/books-vue-1.html 。
新建文件 books-vue-2.html 。
<html>
<head>
<meta charset="utf-8" />
<title>图书 - 组合式API</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<ul>
<li v-for="record in records" :key="record.id">{{ record.name }}</li>
</ul>
</div>
<script>
const { createApp, ref, onMounted } = Vue;
createApp({
setup() {
const records = ref([]);
onMounted(async () => {
try {
const response = await fetch('/books.json');
const data = await response.json();
records.value = data;
} catch (error) {
console.error(error);
}
});
return {
records
};
}
}).mount('#app');
</script>
</body>
</html>访问 http://localhost/books-vue-2.html 。