使用vite + vue3 + pinia + ElementPlus 搭建后台管理项目

考虑到不是所有人都会ts,本文中所有的代码都是以js为主

1. 环境搭建

1. 默认大家都已经搭建好vite及其相关的环境

如有疑问可查看官方文档:vite中文官方文档

2. 使用命令行快速初始化项目:

# npm 6.x
npm init vite@latest my-vue-app --template vue

# npm 7+, 需要额外的双横线:
npm init vite@latest my-vue-app -- --template vue

# yarn
yarn create vite my-vue-app --template vue

# pnpm
pnpm create vite my-vue-app -- --template vue

成功后如下图所示

WX20220420-131346@2x.png

3. 运行项目

  • 这是基本的项目结构

image.png

  • 在vscode中打开终端,先npm install安装依赖,然后运行npm run dev打开浏览器,一个基本的项目就搭建成功了

chenggong.png

2、配置vite

vite.config.js中,配置一下开发中常用的,比如:别名、代理啥的

import {fileURLToPath, URL} from 'url'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    // 别名
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
    // 省略文件扩展名
    extensions: ['.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
  },
  server: {
    // 自动打开浏览器
    open: true,
    // 设置 https 代理
    proxy: {
      '/api': {
        target: 'your https address',
        changeOrigin: true,
        rewrite: path => path.replace(/^\/api/, '')
      }
    }
  }
})

3、使用vue-router4

1. 安装

npm install vue-router@latest

2. 创建路由文件

新建src/router目录并在其下面创建 index.js

import {createRouter, createWebHashHistory} from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/about',
    name: 'about',
    meta: {
      title: '关于'
    },
    component: () => import(/* webpackChunkName: "about" */ '@/views/about')
  },
  {
    path: '/home',
    name: 'home',
    meta: {
      title: '主页'
    },
    component: () => import(/* webpackChunkName: "home" */ '@/views/home')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  document.title = to.meta.title || 'Admin'
  next()
  // do something
})
router.afterEach((to, from) => {
  // do something
})


export default router

3. 创建测试view

新建src/views目录,并新建about.vue和home.vue

// home.vue

<template>
  <div>
    home
  </div>
</template>
// about.vue

<template>
  <div>
    about
  </div>
</template>

4. 在 main.js中引入并使用

import {createApp} from 'vue'
import router from './router'
import App from './App.vue'

const app = createApp(App)

app.use(router)
app.mount('#app')

5. 修改app.vue

<template>
  <div>
    <button @click="$router.push('/home')">home</button>
    <button @click="$router.push('/about')">about</button>
  </div>

  <router-view></router-view>
</template>

4、使用scss

这里为什么使用scss呢,因为UI我们会使用element-plus,所以搭配起来使用更合适

1. 安装

npm i sass sass-loader -D

image.png

2. 创建scss文件

新建src/assets/styles用于存放公共的样式文件,在里面新建一个common.scss, 随便写点样式

image.png

3. app.vue中引入common.scss

<template>
  <div>
    <button class="color" @click="$router.push('/home')">home</button>
    <button @click="$router.push('/about')">about</button>
  </div>

  <router-view></router-view>
</template>

<style lang="scss">
@import '@/assets/styles/common.scss';
</style>

image.png

5、使用pinia

1. 安装

`npm i pinia --save`

2.使用

  1. 新建src/store,在里面新建index.js

registerStore(),其作用是把整个项目的store都提前注册好,最后把所有的store实例挂到appStore透传出去.这样以后,只要我们在项目任何组件要使用pinia时,只要import appStore进来,取对应的store实例就行。

import userStore from './user'
const appStore = {}

export const registerStore = () => {
  appStore.userStore = userStore()
}

export default appStore
  1. 新建src/store/user.js

既然用上了vue3,那就肯定用ref或者reactive啊,这样可以让结构更加扁平化,个人推荐推荐使用这种方式

import {ref} from 'vue'
import {defineStore} from 'pinia'

const userStore = defineStore('USER_INFO', () => {
  const token = ref('this is a token')
  const userInfo = ref({
    name: 'test',
    age: 18,
    work: 'coder'
  })

  function updateUserInfo(user) {
    userInfo.value = user
  } 

  return {token, userInfo, updateUserInfo}
})

export default userStore
  1. 全局注册
import {createApp} from 'vue'
import {createPinia} from 'pinia'
import {registerStore} from '@/store'
import router from './router'
import App from './App.vue'

const app = createApp(App)

app.use(router)
app.use(createPinia())
registerStore()

app.mount('#app')

  1. 测试store

app.vue

<template>
  <div>
    <button class="color" @click="$router.push('/home')">home</button>
    <button @click="$router.push('/about')">about</button>
  </div>

  <router-view></router-view>
</template>

<script setup>
import useUserStore from '@/store/user'

const userStore = useUserStore()

console.log(userStore)
</script>

<style lang="scss">
@import '@/assets/styles/common.scss';
</style>

image.png

6、使用axios

  1. 安装:npm i axios qs --save

2、简单封装axios

新建src/service/request.js

import axios from 'axios'
import router from '@/router'

axios.defaults.baseURL = httpUrl
axios.defaults.withCredentials = true
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers['token'] = '你的token' || ''
axios.defaults.headers.post['Content-Type'] = 'application/json'

// 响应拦截  
axios.interceptors.response.use(res => {
  if (typeof res.data !== 'object') {
    alert('服务端异常!')
    return Promise.reject(res)
  }
  if (res.data.resultCode !== 200) {
    const {message, resultCode} = res.data
    message && console.error(message)
    if (resultCode === 416) {
      // 此处应该删除本地token,removeToken()
      // 需要重新登录
      router.replace({path: '/login'})
    }
    if (res.data.data && window.location.hash == '#/login') {
      const token = res.data.data
      // 缓存服务端token,setToken()
      axios.defaults.headers['token'] = token
    }
    return Promise.reject(res)
  }

  return res.data
}, err => {
  console.log(err)
})

export default axios
  1. 使用
import request from '@/service/request'

request({
    url: 'xxx/com/xxxx',
    method: 'get/post',
    data/params: {},
    ....
})

7、Element-Plus

1、安装

# NPM
$ npm install element-plus --save

# Yarn
$ yarn add element-plus

# pnpm
$ pnpm install element-plus

2、按需加载

安装相关依赖:npm i vite-plugin-style-import --save-dev

修改vite配置

...
import styleImport from 'vite-plugin-style-import'


export default defineConfig({
    ...
    plugins: [
        vue(),
        styleImport({
            libs: [
                {
                    libraryName: 'element-plus',
                    esModule: true,
                    resolveStyle: (name) => {
                        return `element-plus/lib/theme-chalk/${name}.css`;
                    },
                    ensureStyleFile: true // 忽略文件是否存在, 导入不存在的CSS文件时防止错误。
                }
            ]
        })
    ],
    ...
})


3、全局注册相关组件

新建src/plugins/element-plus.js

import {
  ElButton, ElInput, ElLoading, ElContainer, ElAside, ElHeader, ElMain, ElProgress, ......
} from 'element-plus'

const components = [
  ElButton, ElInput, ElContainer, ElAside, ElHeader, ElMain, ElProgress, ......
]

const plugins = [ElLoading, ElDialog, ElMessage]

const ElementPlus = {
  install: (App) => {
    components.forEach(component => App.component(component.name, component))
    plugins.forEach(plugin => App.use(plugin))
    // 全局配置
    App.config.globalProperties.$element = {size: 'small', zIndex: 3000}
  }
}

export default ElementPlus

在main.js中注册

import {createApp} from 'vue'
import {createPinia} from 'pinia'
import {registerStore} from '@/store'
import router from './router'
import ElementPlusComp from './plugins/element-plus'
import App from './App.vue'

const app = createApp(App)

app.use(router)
app.use(createPinia())
app.use(ElementPlusComp)
registerStore()

app.mount('#app')

8、 使用 commitizen 规范git提交

  1. 安装
npm install -D commitizen cz-conventional-changelog @commitlint/config-conventional @commitlint/cli commitlint-config-cz cz-customizable
复制代码
  1. 配置 package.json
{
  ...
  "scripts": {
    "commit:comment": "引导设置规范化的提交信息",
    "commit":"git-cz",
  },

  "config": {
      "commitizen": {
        "path": "node_modules/cz-customizable"
      }
  },
  ...
}

  1. 根目录新增配置 commitlint.config.js
module.exports = {
    extends: ['@commitlint/config-conventional', 'cz'],
    rules: {
        'type-enum': [
            2,
            'always',
            [
                'feature', // 新功能(feature)
                'bug', // 此项特别针对bug号,用于向测试反馈bug列表的bug修改情况
                'fix', // 修补bug
                'ui', // 更新 ui
                'docs', // 文档(documentation)
                'style', // 格式(不影响代码运行的变动)
                'perf', // 性能优化
                'release', // 发布
                'deploy', // 部署
                'refactor', // 重构(即不是新增功能,也不是修改bug的代码变动)
                'test', // 增加测试
                'chore', // 构建过程或辅助工具的变动
                'revert', // feat(pencil): add ‘graphiteWidth’ option (撤销之前的commit)
                'merge', // 合并分支, 例如: merge(前端页面): feature-xxxx修改线程地址
                'build', // 打包
            ],
        ],
        // <type> 格式 小写
        'type-case': [2, 'always', 'lower-case'],
        // <type> 不能为空
        'type-empty': [2, 'never'],
        // <scope> 范围不能为空
        'scope-empty': [2, 'never'],
        // <scope> 范围格式
        'scope-case': [0],
        // <subject> 主要 message 不能为空
        'subject-empty': [2, 'never'],
        // <subject> 以什么为结束标志,禁用
        'subject-full-stop': [0, 'never'],
        // <subject> 格式,禁用
        'subject-case': [0, 'never'],
        // <body> 以空行开头
        'body-leading-blank': [1, 'always'],
        'header-max-length': [0, 'always', 72],
    },
};

  1. 自定义提示则添加 .cz-config.js
module.exports = {
    types: [
        {value: 'feature',  name: 'feature:  增加新功能'},
        {value: 'bug',      name: 'bug:      测试反馈bug列表中的bug号'},
        {value: 'fix',      name: 'fix:      修复bug'},
        {value: 'ui',       name: 'ui:       更新UI'},
        {value: 'docs',     name: 'docs:     文档变更'},
        {value: 'style',    name: 'style:    代码格式(不影响代码运行的变动)'},
        {value: 'perf',     name: 'perf:     性能优化'},
        {value: 'refactor', name: 'refactor: 重构(既不是增加feature,也不是修复bug)'},
	{value: 'release',  name: 'release:  发布'},
	{value: 'deploy',   name: 'deploy:   部署'},
        {value: 'test',     name: 'test:     增加测试'},
        {value: 'chore',    name: 'chore:    构建过程或辅助工具的变动(更改配置文件)'},
        {value: 'revert',   name: 'revert:   回退'},
    	{value: 'build',    name: 'build:    打包'}
    ],
    // override the messages, defaults are as follows
    messages: {
        type: '请选择提交类型:',
        customScope: '请输入您修改的范围(可选):',
        subject: '请简要描述提交 message (必填):',
        body: '请输入详细描述(可选,待优化去除,跳过即可):',
        footer: '请输入要关闭的issue(待优化去除,跳过即可):',
        confirmCommit: '确认使用以上信息提交?(y/n/e/h)'
    },
    allowCustomScopes: true,
    skipQuestions: ['body', 'footer'],
    subjectLimit: 72
};
  • 0
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是搭建后台管理系统的简单步骤: 1. 创建项目 使用 Vue CLI 创建项目,选择 vue3 preset,安装完成后进入项目目录。 ``` vue create my-project cd my-project ``` 2. 安装依赖包 安装 vitevue-router 和 element-plus。 ``` npm install vite vue-router@4 element-plus --save ``` 安装 pinia 和 echarts。 ``` npm install pinia echarts@5 --save ``` 3. 配置 vite 在根目录下创建 `vite.config.js` 文件,配置 alias 和 server。 ```js import path from 'path' import { defineConfig } from 'vite' export default defineConfig({ resolve: { alias: { '@': path.resolve(__dirname, 'src'), }, }, server: { port: 3000, open: true, }, }) ``` 4. 配置路由 在 `src` 目录下创建 `router` 文件夹,并创建 `index.js` 文件,配置路由。 ```js import { createRouter, createWebHistory } from 'vue-router' import Home from '@/views/Home.vue' const routes = [ { path: '/', name: 'Home', component: Home, }, ] const router = createRouter({ history: createWebHistory(), routes, }) export default router ``` 在 `src` 目录下的 `main.js` 中引入路由。 ```js import { createApp } from 'vue' import App from './App.vue' import router from './router' const app = createApp(App) app.use(router) app.mount('#app') ``` 5. 配置状态管理 在 `src` 目录下创建 `store` 文件夹,并创建 `index.js` 文件,配置状态管理。 ```js import { createPinia } from 'pinia' const store = createPinia() export default store ``` 在 `src` 目录下的 `main.js` 中引入状态管理。 ```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) app.use(store) app.mount('#app') ``` 6. 配置 UI 框架 在 `src` 目录下的 `main.js` 中引入 element-plus。 ```js import { createApp } from 'vue' import App from './App.vue' import router from './router' import store from './store' import ElementPlus from 'element-plus' import 'element-plus/lib/theme-chalk/index.css' const app = createApp(App) app.use(router) app.use(store) app.use(ElementPlus) app.mount('#app') ``` 7. 配置 echarts 在 `src` 目录下的 `main.js` 中引入 echarts。 ```js import { createApp } from 'vue' import App from './App.vue' import router from './router' import store from './store' import ElementPlus from 'element-plus' import 'element-plus/lib/theme-chalk/index.css' import * as echarts from 'echarts' const app = createApp(App) app.use(router) app.use(store) app.use(ElementPlus) app.config.globalProperties.$echarts = echarts app.mount('#app') ``` 8. 创建页面 在 `src` 目录下创建 `views` 文件夹,并创建页面组件。 9. 创建布局 在 `src` 目录下创建 `layouts` 文件夹,并创建布局组件。 10. 配置路由和布局 在 `router/index.js` 中配置路由和布局。 ```js import { createRouter, createWebHistory } from 'vue-router' import Layout from '@/layouts/Layout.vue' import Home from '@/views/Home.vue' const routes = [ { path: '/', component: Layout, children: [ { path: '', name: 'Home', component: Home, }, ], }, ] const router = createRouter({ history: createWebHistory(), routes, }) export default router ``` 11. 运行项目项目根目录下运行 `npm run dev`,打开浏览器访问 `http://localhost:3000` 查看效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值