使用vite创建vue3项目
使用vite搭建带有typescript+vue-router+vuex的vue3项目
·
1.创建项目
npm init vite@latest
依次输入项目名称、选择vue、选择使用js或者ts
2.引入依赖
cd 项目名称
npm install
3.启动项目
npm run dev
4.引入vue-router
npm install vue-router@4 -S
在src目录下新建router/index.ts并编写一下代码
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
component: () => import('../components/HelloWorld.vue')
}
]
const router = createRouter({
// createWebHashHistory hash 路由
// createWebHistory history 路由
// createMemoryHistory 带缓存 history 路由
history: createWebHistory(),
routes
})
export default router
然后修改main.ts文件为:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
继续修改App.vue文件为:
<script setup lang="ts">
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup</script>
<template>
<img alt="Vue logo" src="./assets/logo.png"/>
<router-view/>
<!-- <HelloWorld msg="Hello Vue 3 + TypeScript + Vite" />-->
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
5.引入vuex
npm install vuex@next --S
src目录下新建store/index.ts并编写一下代码
import { createStore } from 'vuex'
const store = createStore({
state: {
userInfo: {
name:'myName'
}
},
mutations: {
getUserInfo (state:any, name:string|number) {
state.userInfo.name = name
}
},
actions: {
asyncGetUserInfo (context:any) {
setTimeout(() => {
context.commit("getUserInfo", +new Date() + 'action')
},2000)
}
},
getters: {
userInfoGetter (state:any) {
return state.userInfo.name
}
}
})
export default store;
继续修改main.ts文件:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from "./store";
createApp(App).use(router).use(store).mount('#app')
ok 大功告成 接下来就可以愉快的编写代码啦
使用了vue3+typescript+vue-router+vuex
更多推荐
已为社区贡献1条内容
所有评论(0)