Simply put, it is to record how to build a vue3+vite+elementplus project from 0,
This article records in detail the code\console and file operations of each step, including project construction\installation of vuerouter\installation of vuex\installation of axios and some pre-release preparations.
It can be said to be a nanny-level tutorial, if you like it, you can bookmark it,
If you have any questions, please discuss them in the comment area
2022/6/2 update
Provide a basic code that has been processed except that it can be used directly after being cloned
git address https://github.com/shinjie1210/vite-config.git
----------------------------------------------------------------------------------------------------------------------------
Table of contents
1. Create and initialize the project
5. Install and use element-plus
6. Preparation for publication
1. Create and initialize the project
console input
npm init vite@latest
Then fill in the project name and project framework by yourself. Here I still choose js. Friends who are interested in ts can understand it by themselves, and it is not complicated.
After cd into the project directory, install it and then run it
In order to make it easier to modify later, and I am lazy, I will set it to run and automatically open it in the default browser
Make the following changes in package.json
{
"name": "a-project",
"version": "0.0.0",
"scripts": {
"dev": "vite --open",//改了这一行 添加了--open
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"vue": "^3.2.25"
},
"devDependencies": {
"@vitejs/plugin-vue": "^2.0.0",
"vite": "^2.7.2"
}
}
Then clean up and clear the default content, leaving a homepage logo on it
<script setup>
</script>
<template>
<img alt="Vue logo" src="./assets/logo.png" />
</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>
It is recommended that everyone who uses vscode use the Vue Language Features (Volar) plugin, which is easier to use
2. Install and use vue-router
npm install vue-router@4
Then create the following files for configuring and testing routes
Configure routing page index
import {
createRouter,
createWebHistory
} from 'vue-router'
const routerHistory = createWebHistory()
const router = createRouter({
history: routerHistory,
routes: [{
path: '/',
}, {
path: '/foo',
component: () => import('../views/foo.vue')
}, {
path: '/bar',
component: () => import('../views/bar.vue')
}]
})
export default router
Test page foo.vue/bar.vue
<template>
<div>this is foo page</div>
</template>
<script setup>
</script>
<style>
</style>
The app.vue page is modified as follows
<script setup>
import {
useRouter
} from 'vue-router'
const router = useRouter()
function toFoo() {
router.push({
path: '/foo'
})
}
function toBar() {
router.push({
path: '/bar'
})
}
</script>
<template>
<div>
<img alt="Vue logo" src="./assets/logo.png" />
</div>
<button @click="toFoo">to foo</button>
<button @click="toBar">to bar</button>
<router-view></router-view>
</template>
<style>
#app {
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Then introduce in main.js
import {
createApp
} from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router).mount('#app')
Then test the effect
3. Install and use vuex
npm i vuex@next -S
Add the following files
Configure index.js
import {
createStore,
} from 'vuex';
export default createStore({
state: {
test: 0
},
mutations: { //同步
add(state) {
state.test++
},
min(state) {
state.test--
},
set99(state, payload) {
state.test = payload
}
},
actions: {
change(context, payload) { //异步
setTimeout(() => {
context.commit('set99', payload)
}, 1500);
}
}
});
Then introduce in main.js
import {
createApp
} from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
const app = createApp(App)
app.use(router).use(store).mount('#app')
Introduce (foo/bar.vue) on other pages and see the effect
<template>
<div>this is foo page</div>
<p>{
{store.state.test}}</p>
</template>
<script setup>
import {
useStore
} from 'vuex'
const store = useStore()
</script>
<style>
</style>
Introduce and test method execution on other pages (app.vue)
<script setup>
import {
useRouter
} from 'vue-router' //引入router
import {
useStore
} from 'vuex' //引入vuex
const router = useRouter()
const store = useStore()
//路由跳转测试
function toFoo() {
router.push({
path: '/foo'
})
}
function toBar() {
router.push({
path: '/bar'
})
}
//修改数据func测试
function addState() {
store.commit('add')
}
function minState() {
store.commit('min')
}
//异步func测试
function changeState() {
store.dispatch('change', 99)
}
</script>
<template>
<div>
<img alt="Vue logo" src="./assets/logo.png" />
</div>
<button @click="toFoo">to foo</button>
<button @click="toBar">to bar</button>
<router-view></router-view>
<div>
<button @click="addState">add</button>
<button @click="minState">min</button>
<button @click="changeState">change</button>
</div>
</template>
<style>
#app {
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
If the effect is as follows, then vuex is introduced successfully
4. Install and use axios
npm install axios
Then add the configuration file
Edit apiManager.js to configure request settings
import axios from 'axios';
class ApiHost {
constructor(baseUrl, name, baseOptions) {
this.name = name;
this.axiosInstance = axios.create({
baseURL: baseUrl,
withCredentials: false,
});
this.baseUrl = baseUrl;
this.baseOptions = baseOptions;
//拦截器,用户识别需不需要token
this.axiosInstance.interceptors.request.use(
config => {
let token = window.localStorage.getItem('token')
if (token && config.url.indexOf('login') == -1) {
config.headers.token = token
}
return config;
},
error => {
return error;
}
)
}
call(path, method, urlParams, bodyParams, options) {
let configs = {
url: `${path}`,
params: urlParams,
method,
data: bodyParams
};
return new Promise((resolve, reject) => {
this.axiosInstance
.request(configs)
.then(res => {
if (res.data.code == '200' || res.data.code == '0') {
resolve(res.data);
} else {
reject(res.data)
}
})
.catch(error => {
reject(error);
});
})
}
get(path, urlParams, options) {
return this.call(path, 'get', urlParams, null, options);
}
delete(path, urlParams, bodyParams, options) {
return this.call(path, 'delete', urlParams, bodyParams, options);
}
post(path, bodyParams, options) {
return this.call(path, 'post', null, bodyParams, options);
}
put(path, bodyParams, options) {
return this.call(path, 'put', null, bodyParams, options);
}
patch(path, bodyParams, options) {
return this.call(path, 'patch', null, bodyParams, options);
}
}
export default class {
static getApiHost(baseUrl, name, baseOptions) {
return new ApiHost(baseUrl, name, baseOptions);
}
}
Edit index.js to export all requests
import ApiManager from '../api/ApiManager'
const apiManager = ApiManager.getApiHost("", "");
//admin-auth-center/login 用户登录
export function userLogin(data) {
return apiManager.post('你的baseURL' + "你的接口路径", data)
}
Then we do a test in app.vue
<script setup>
import {
useRouter
} from 'vue-router' //引入router
import {
useStore
} from 'vuex' //引入vuex
import { //引入生命周期函数--------------------添加内容
onMounted
} from 'vue';
import { //引入定义的请求--------------------添加内容
userLogin
} from './api/index'
const router = useRouter()
const store = useStore()
//发请求--------------------添加内容
onMounted(() => {
userLogin({
//你的请求字段
}).then(res => {
console.log(res);
}).catch(error => {
console.log(error);
})
})
//路由跳转测试
function toFoo() {
router.push({
path: '/foo'
})
}
function toBar() {
router.push({
path: '/bar'
})
}
//修改数据func测试
function addState() {
store.commit('add')
}
function minState() {
store.commit('min')
}
//异步func测试
function changeState() {
store.dispatch('change', 99)
}
</script>
<template>
<div>
<img alt="Vue logo" src="./assets/logo.png" />
</div>
<button @click="toFoo">to foo</button>
<button @click="toBar">to bar</button>
<router-view></router-view>
<div>
<button @click="addState">add</button>
<button @click="minState">min</button>
<button @click="changeState">change</button>
</div>
</template>
<style>
#app {
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Then if the console prints the request result, it is considered successful
5. Install and use element-plus
First npm install it, and then we go directly to the on-demand import route
npm install element-plus --save
Install on-demand plugins
npm install -D unplugin-vue-components unplugin-auto-import
Then go to edit vite.config.js
import {
defineConfig
} from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'//这里
import AutoImport from 'unplugin-auto-import/vite'//这里
import {
ElementPlusResolver
} from 'unplugin-vue-components/resolvers'//这里
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(),
AutoImport({//这里
resolvers: [ElementPlusResolver()],
}),
Components({//这里
resolvers: [ElementPlusResolver()],
}),
]
})
So here we have successfully completed the on-demand import, and no longer need to import it separately on each page.
Write some content below for testing, just test it directly on the app.vue page
First write an el-button in the dom to see if it can be displayed, the location is random, you can find it yourself
<el-button type="primary">ele-test</el-button>
Then test whether ElMessage can be used without a separate introduction in the place where the request was written before
onMounted(() => {
ElMessage({
message: 'element-plus按需引入成功',
type: 'success',
})
})
ojbk
6. Preparation for publication
It’s a little early today.. Let’s write a little more about what training institutions and online videos don’t say
After the project is set up, you can publish the version on the intranet to see the effect. Let's do some preparatory work
First go to the routing index page and write the route history mode path,
import {
createRouter,
createWebHistory
} from 'vue-router'
const routerHistory = createWebHistory('/aProject/')//这里
const router = createRouter({
history: routerHistory,
routes: [{
path: '/',
}, {
path: '/foo',
component: () => import('../views/foo.vue')
}, {
path: '/bar',
component: () => import('../views/bar.vue')
}]
})
export default router
Then modify the content of vite.config.js, configure the project deployment base directory, and the address is consistent with the routing path just configured
import {
defineConfig,
loadEnv
} from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import {
ElementPlusResolver
} from 'unplugin-vue-components/resolvers'
// https://vitejs.dev/config/
export default defineConfig({
base: '/aProject/',//这里
plugins: [vue(),
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
]
})
Then modify the .gitignore file, the default is not to upload the dist folder, we need to modify it
node_modules
.DS_Store
#dist//可以加#号也可以直接删除本行
dist-ssr
*.local
Then run build on the command line, you can let the operation and maintenance deploy the project according to the dist folder
npm run build
If I have time in these two days, I will write about the subcontracting in different environments and the configuration of vite.config. If you find it useful, remember to give it a thumbs up.