创建一个简单的单页应用(SPA)
下面是创建一个简单的单页应用(SPA)的步骤,结合 Vue 3 的核心特性,包括 Vue Router、Pinia(状态管理)和 Axios(HTTP 请求)。
1. 项目初始化
首先,使用 Vue CLI 创建一个新的 Vue 3 项目:
bash
npm install -g @vue/cli
vue create vue-spa
cd vue-spa选择 Vue 3 配置。
2. 安装依赖
安装 Vue Router、Pinia 和 Axios:
bash
npm install vue-router pinia axios3. 创建基本文件结构
在 src 目录下,创建以下文件结构:
text
src/
├── api/
│ └── api.js
├── components/
│ ├── Home.vue
│ └── About.vue
├── store/
│ └── store.js
├── router/
│ └── index.js
└── App.vue4. 设置 Axios
在 src/api/api.js 中配置 Axios:
javascript
import axios from 'axios';
const api = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com', // 示例 API
timeout: 5000,
});
export default api;5. 配置 Pinia
在 src/store/store.js 中配置 Pinia:
javascript
import { defineStore } from 'pinia';
import api from '../api/api';
export const useMainStore = defineStore('main', {
state: () => ({
posts: [],
}),
actions: {
async fetchPosts() {
const response = await api.get('/posts');
this.posts = response.data;
},
},
});6. 配置 Vue Router
在 src/router/index.js 中配置路由:
javascript
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../components/Home.vue';
import About from '../components/About.vue';
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;7. 创建组件
在 src/components/Home.vue 中创建主页组件:
vue
<template>
<div>
<h1>首页</h1>
<button @click="loadPosts">加载帖子</button>
<ul>
<li v-for="post in posts" :key="post.id">{{ post.title }}</li>
</ul>
</div>
</template>
<script setup>
import { ref } from 'vue';
import { useMainStore } from '../store/store';
const store = useMainStore();
const posts = ref([]);
const loadPosts = async () => {
await store.fetchPosts();
posts.value = store.posts;
};
</script>在 src/components/About.vue 中创建关于页组件:
vue
<template>
<div>
<h1>关于页面</h1>
<p>这是一个简单的单页应用。</p>
</div>
</template>8. 更新 App.vue
在 src/App.vue 中设置导航和路由视图:
vue
<template>
<div id="app">
<nav>
<router-link to="/">首页</router-link>
<router-link to="/about">关于</router-link>
</nav>
<router-view />
</div>
</template>9. 主入口文件
在 src/main.js 中配置 Pinia 和 Router:
javascript
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { createPinia } from 'pinia';
const app = createApp(App);
app.use(router);
app.use(createPinia());
app.mount('#app');10. 启动应用
最后,启动应用:
bash
npm run serve11. 总结
现在,你可以访问 http://localhost:8080,看到一个简单的单页应用,其中包含 Vue Router 实现的页面切换、Pinia 进行状态管理和 Axios 进行数据请求的功能。点击“加载帖子”按钮后,会从 API 加载帖子数据并在主页显示。你可以根据需要进一步扩展和优化此应用。