vue3+vite+ts这个项目 加入router axios vuex
时间: 2023-09-03 13:07:08 浏览: 142
1. 安装路由、axios和vuex
```bash
npm install vue-router axios vuex --save
```
2. 创建路由
在src/router目录下创建index.ts文件,并添加以下内容:
```typescript
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Home from '@/views/Home.vue'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: Home
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
```
3. 创建Vuex store
在src/store目录下创建index.ts文件,并添加以下内容:
```typescript
import { createStore } from 'vuex'
export default createStore({
state: {},
mutations: {},
actions: {},
modules: {}
})
```
4. 在main.ts中使用路由、axios和vuex
在main.ts文件中添加以下内容:
```typescript
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
const app = createApp(App)
app.config.globalProperties.$axios = axios
app.use(router)
app.use(store)
app.mount('#app')
```
5. 在组件中使用路由、axios和vuex
在组件中可以直接使用路由、axios和vuex,例如:
```typescript
import { defineComponent } from 'vue'
import { useStore } from 'vuex'
export default defineComponent({
setup() {
const store = useStore()
const fetchData = async () => {
const res = await axios.get('/api/data')
store.dispatch('setData', res.data)
}
return {
fetchData
}
}
})
```
```typescript
import { defineComponent } from 'vue'
import { useRouter } from 'vue-router'
export default defineComponent({
setup() {
const router = useRouter()
const goToPage = (pageName: string) => {
router.push({ name: pageName })
}
return {
goToPage
}
}
})
```
阅读全文
相关推荐
![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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)
![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)
![7z](https://img-home.csdnimg.cn/images/20241231044736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)