vite+vue3.0+vue-router+vuex快速搭建项目
vite是类似webpack的前端构建工具,基于浏览器 ES module ,优点:
- 快速的冷启动
- 即时的模块热更新
- 真正的按需编译
首先全局安装create-vite-app
npm install create-vite-app -g
创建项目
cva vue3 // 或者 npx create-vite-app vue3
安装依赖以及启动、打包命令
cd vue3 npm install npm run dev npm run build
引入vue-router4.0
npm install vue-router@4
src目录下新建router/index.js
index.js:
import { createRouter, createWebHistory } from 'vue-router' import HelloWorld from '../components/HelloWorld.vue' const routerHistory = createWebHistory() // createWebHashHistory hash 路由 // createWebHistory history 路由 // createMemoryHistory 带缓存 history 路由 const router = createRouter({ history: routerHistory, routes: [ { path: '/', component: HelloWorld }, ] }) export default router
main.js:
import { createApp } from 'vue' import App from './App.vue' import './index.css' import router from './router' const app = createApp(App) app.use(router) app.mount('#app') // createApp(App).mount('#app')
app.vue:
<template> <router-view></router-view> </template> <script> export default { name: 'App', } </script>
引入vuex4.0
npm install vuex@next --save
src目录下新建store/index.js
index.js:
import { createStore } from 'vuex' const store = createStore({ state: { userInfo: { name:'myName' } }, mutations: { getUserInfo (state, name) { state.userInfo.name = name } }, actions: { asyncGetUserInfo ({ commit }) { setTimeout(() => { commit("getUserInfo", +new Date() + 'action') },2000) } }, getters: { userInfoGetter (state) { return state.userInfo.name } } }) export default store
main.js:
import { createApp } from 'vue' import App from './App.vue' import './index.css' import router from './router' import store from './store' const app = createApp(App) app.use(router) app.use(store) app.mount('#app') // createApp(App).use(router).use(store).mount('#app')
前端交流群,群文件提供大量文档、书籍和资料。期待你的加入!群号:127768464