赞
踩
简单来说就是记录一下怎么从0开始搭建一个vue3+vite+elementplus的项目,
本文详细记录了每一步的代码\控制台和文件操作,包括项目搭建\安装vuerouter\安装vuex\安装axios和一些发版前准备工作,
可以说是保姆级教程了,喜欢可以收藏一下,
有问题大家一起在评论区探讨
2022/6/2更新
提供一个除了都处理好了的基础代码,clone下来可以直接使用
git地址https://github.com/shinjie1210/vite-config.git
----------------------------------------------------------------------------------------------------------------------------
目录
控制台输入
npm init vite@latest
然后自己填下项目名称和项目框架 这里我还是选择js的,感兴趣ts的朋友可以自己了解下,也不复杂
cd进项目目录后install一下就可以run起来了
为了方便后面修改啥的,再加上我这个人比较懒,就去设置一下run之后自动默认浏览器打开
在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"
- }
- }
然后清理一下 把默认的内容都清空了,留一个主页logo就可以了
- <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>
推荐用vscode的各位使用 Vue Language Features (Volar) 这个插件 比较好用
npm install vue-router@4
然后新建如下文件用于配置和测试路由
配置路由页面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
测试页面foo.vue/bar.vue
- <template>
- <div>this is foo page</div>
- </template>
- <script setup>
- </script>
- <style>
- </style>
app.vue页面进行如下修改
- <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>
然后在main.js里引入
- import {
- createApp
- } from 'vue'
- import App from './App.vue'
- import router from './router'
- const app = createApp(App)
- app.use(router).mount('#app')
那么测试下效果
npm i vuex@next -S
新增以下文件
配置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);
- }
- }
- });
然后在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')
在其他页面引入(foo/bar.vue)并查看效果
- <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>
在其他页面引入并测试方法执行(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>
效果如下的话,那么vuex就算引入成功了
npm install axios
然后添加配置文件
编辑apiManager.js 用来配置请求设置
- 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);
- }
- }
编辑index.js用于导出所有请求
- import ApiManager from '../api/ApiManager'
- const apiManager = ApiManager.getApiHost("", "");
- //admin-auth-center/login 用户登录
- export function userLogin(data) {
- return apiManager.post('你的baseURL' + "你的接口路径", data)
- }
然后我们在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>
那么如果控制台打印了请求结果,就算成功拉
先npm安装一下,然后我们直接走按需引入路线
npm install element-plus --save
安装按需引入的插件
npm install -D unplugin-vue-components unplugin-auto-import
然后去编辑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()],
- }),
- ]
- })
那么到这里我们就成功完成按需引入了,不再需要在每个页面单独进行引入了,
下面写点内容进行测试,直接在app.vue页面测试就行了
先在dom里写个el-button看能不能显示,位置随便啊自己好找就行
<el-button type="primary">ele-test</el-button>
然后再在之前写请求的地方测试下ElMessage在没有单独引入的情况下能不能使用
- onMounted(() => {
- ElMessage({
- message: 'element-plus按需引入成功',
- type: 'success',
- })
- })
ojbk
今天有点早..就再写一点培训机构和网上视频不怎么说的内容
项目搭起来之后可以内网发版看下效果了,我们做一下准备工作
首先前往路由index页面写一下路由history模式路径,
- 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
然后再修改vite.config.js内容,配置项目部署基础目录,地址和刚刚配置的路由路径一致
- 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()],
- }),
- ]
- })
之后再修改一下.gitignore文件,默认是不上传dist文件夹的 我们需要修改一下
- node_modules
- .DS_Store
- #dist//可以加#号也可以直接删除本行
- dist-ssr
- *.local
然后命令行运行build,就可以让运维把按dist文件夹部署项目了
npm run build
这两天有空我再写一下不同环境的分包和vite.config的配置,觉得有用的朋友记得点赞哦
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。