1 安装yarn并创建vue3项目
npm install -g yarn
yarn create vite
cd vite-project
yarn
yarn dev
# 注:已有项目使用 yarn install安装依赖包
- 打开vite.config.js文件配置一下路径别名 @
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
"@": path.resolve(__dirname, "src"),
},
},
})
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "Node",
"strict": true,
"jsx": "preserve",
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"lib": [
"ESNext",
"DOM"
],
"skipLibCheck": true,
"baseUrl": "./",# 添加
"paths": {# 添加
"@/*": [
"src/*"
]
},
"noEmit": true
},
"include": [
"src/**/*.ts",
"src/**/*.d.ts",
"src/**/*.tsx",
"src/**/*.vue"
],
"references": [
{
"path": "./tsconfig.node.json"
}
]
}
2 安装 pinia
yarn add pinia
- 在src里面创建一个store文件夹 在创建一个index.ts文件
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
state: () => ({
name: '你好陌生人!'
})
})
- 在main.ts里面添加pinia实例 注意要放在mount("#app")前面
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import {createPinia} from 'pinia' #导入pinia
const pinia=createPinia();#创建pinia,并在vue实例中use(pinia)
createApp(App).use(pinia).mount('#app')
- 在src里面创建一个views文件夹 在创建一个home.vue文件
<template>
<h1>{{ stores.name }} 你好, vite + vue3 + TS + vue-router + pinia</h1>
</template>
<script setup lang="ts">
import { useStore } from "@/store/index"
const stores = useStore()
</script>
- app.vue文件这里我们将默认的替换成home.vue
<script setup lang="ts">
import Home from '@/components/home.vue'
</script>
<template>
<Home msg="测试"/>
</template>
<style scoped>
</style>
3 安装开始vue-router路由
yarn add vue-router@4
- src里面创建一个router文件夹 在创建一个index.ts文件
import { createRouter, createWebHistory } from "vue-router";
export const router = createRouter({
history: createWebHistory(),
routes: [
{
path: "/",
name: "home",
component: () => import("@/components/home.vue"),
},
],
});
- 在main.ts里面添加router实例 注意要放在mount("#app")前面
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import {createPinia} from 'pinia'
import { router } from './router'# 导入router
const pinia=createPinia();
createApp(App).use(pinia).use(router).mount('#app')
<script setup lang="ts">
// import Home from '@/components/home.vue'
</script>
<template>
<router-link to="/"></router-link>
<router-view></router-view>
</template>
<style scoped>
</style>