从0搭建一个工程可以更清楚的了解工程的组成,对工程的依赖、配置和运行理解更深入,以后搭建自己脚手架,生成自己的模板工程,提高效率。
技术栈
- Vite3.x
- Vue3.2
- TypeScript
- Vuex4.x
- Vue Router4.x
- CSS3
准备
- node.js版本需要大于12.0.0
- npm
创建项目
根据vue3官网生成模板工程:https://v3.cn.vuejs.org/guide/installation.html#vite
记得将project-name换成自己项目的名字:
1
| npm init vite@latest <project-name> --template vue
|
1.选择vue:
2.选择vue-ts:
3.看到这里就已经创建成功了:
4.根据提示启动工程:
cd vue3-demo npm install npm run dev
5.访问本地http://127.0.0.1:5173/:
至此,工程创建成功,接下来需要一步一步根据项目需要安装和配置项目所需的依赖。
安装依赖
如果使用的是vscode编辑器,需要禁用Vetur插件,安装Vue Language Features (Volar)插件。
1.安装路由
1
| npm install vue-router@4
|
配置路由:
在src根目录下建立/router/index.ts文件,路由配置例子如下:
/src/router/index.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router' import Layout from '../components/HelloWorld.vue' const routes: Array<RouteRecordRaw> = [ { path: '/', name: 'Home', component: Layout } ] const router = createRouter({ history: createWebHistory(), routes }) export default router
|
App.vue
1 2 3 4 5
| <template> <router-view/> </template> <style lang="scss"> </style>
|
main.ts
1 2 3 4 5 6
| import { createApp } from 'vue' import './style.css' import App from './App.vue' import router from './router'
createApp(App).use(router).mount('#app')
|
2.安装vuex
1
| npm install vuex@next --save
|
建立/store/index.ts文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import { InjectionKey } from 'vue' import { createStore, useStore as baseUseStore, Store } from 'vuex' export interface State { count: number } export const key: InjectionKey<Store<State>> = Symbol() export const store = createStore<State>({ state: { count: 0 }, mutations:{ setCount(state:State,count:number){ state.count = count } }, getters:{ getCount(state:State){ return state.count } } })
export function useStore () { return baseUseStore(key) }
|
修改main.ts
1 2 3 4 5 6 7
| import { createApp } from 'vue' import './style.css' import App from './App.vue' import router from './router' import { store, key } from './store'
createApp(App).use(store, key).use(router).mount('#app')
|
修改HelloWorld.vue文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <script setup lang="ts"> import { ref, computed } from "vue" import { useStore } from "../store" const store = useStore() const count = ref(0) const showcount = computed(() => { return store.getters["getCount"] }) const addBtn = () => { store.commit("setCount", ++count.value) } </script> <template> <p>{{ showcount }}</p> <button @click="addBtn">增加</button> </template> <style scoped></style>
|
至此,vue-router和Vuex安装配置好了, 下面需要安装eslint,css预处理器及sass安装.