vue-router 和 vuex 安装
由于 vite 创建的 vue 脚手架不支持顺带 vue-router 和 vuex 的安装,这里需要手动安装一下,到项目目录下使用 npm 安装:
npm install vue-router vuex
等待安装完成,没报错就行。
相关文件及配置
在 src 下创建 router
、store
、views
三个目录,并创建相应的文件,更新部分的结构如下:
src
├── router
│ └── index.js
├── store
│ └── index.js
└── views
├── AboutView.vue
└── HomeView.vue
相应代码直接复制即可:
router/index.js
import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import('../views/AboutView.vue')
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
view/AboutView.vue
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
view/HomeView.vue
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.svg">
</div>
</template>
<script setup>
</script>
store/index.js
import { createStore } from 'vuex'
export default createStore({
state: {
},
getters: {
},
mutations: {
},
actions: {
},
modules: {
}
})
最后,需要在 main.js
将配置加载进app 里:
import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
// createApp(App).mount('#app')
const app = createApp(App)
app.use(store).use(router).mount('#app')
完事儿,让vite run 起来!