vite+vue3+ts路由vue-router调接口
时间: 2023-07-29 08:08:59 浏览: 208
在 Vite + Vue 3 + TypeScript 的项目中,你可以使用 Vue Router 来处理路由,并调用接口。
首先,确保你已经安装了 Vue Router 和 axios(或其他用于发送 HTTP 请求的库)。你可以使用以下命令进行安装:
```
npm install vue-router axios
```
接下来,在你的项目中创建一个 `router` 文件夹,并在其中创建一个 `index.ts` 文件。在该文件中,你可以配置你的路由。以下是一个示例:
```typescript
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import Home from '@/views/Home.vue';
import About from '@/views/About.vue';
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/about',
name: 'About',
component: About,
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
```
在上面的示例中,我们定义了两个路由:`Home` 和 `About`。你可以根据你的需求进行修改和扩展。
然后,在你的入口文件(如 `main.ts`)中,引入并使用你的路由:
```typescript
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
```
现在,你可以在你的组件中使用 `vue-router` 进行路由导航和调用接口。例如,在 `Home.vue` 组件中,你可以这样使用:
```vue
<template>
<div>
<h1>Home</h1>
<button @click="fetchData">Fetch Data</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
methods: {
fetchData() {
axios.get('/api/data').then((response) => {
console.log(response.data);
}).catch((error) => {
console.error(error);
});
},
},
};
</script>
```
在上面的示例中,我们使用了 axios 发送 GET 请求来获取数据。你可以根据你的需求调整和扩展这个例子。
希望这能帮助到你!如果你有任何其他问题,请随时问我。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)