zxpnet网站 zxpnet网站
首页
前端
后端服务器
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

zxpnet

一个爱学习的java开发攻城狮
首页
前端
后端服务器
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 大前端课程视频归档
  • html

  • js

  • 前端框架

  • 自动化构建

  • typescript

  • es6

  • bootstrap

  • layer

  • vue

  • vue3

    • 邂逅Vue3和Vue3开发体验
    • Vue3基础语法
    • Vue3组件化开发
    • Vue3过渡&动画实现
    • Babel和devServer
    • Composition API
    • vue3高级语法
    • vue3源码
    • vue-router路由
    • vuex状态管理
    • vue开源项目
    • vue3-cms项目笔记
      • vue-cli搭建
      • 一、代码规范
        • 1.1. 集成editorconfig配置
        • 1.2. 使用prettier工具
        • 1.3. 使用ESLint检测
        • 规则rules
        • 1.4. git Husky和eslint
        • 1.5. git commit规范
        • 1.5.1. 代码提交风格
        • 1.5.2. 代码提交验证
      • 二、区分不同环境
      • 三. 第三方库集成
        • 2.1. vue.config.js配置
        • 2.2. vue-router集成
        • 2.3. vuex集成
        • 2.4. element-plus集成
        • 2.4.1. 全局引入
        • 2.4.2. 局部引入
        • 2.5. axios集成
        • axios请求方式
        • axios的配置选项
        • axios的拦截器
        • 封装axios:
        • 2.6. VSCode配置
      • 四. 接口文档
      • vuex
        • 给state给定类型
        • 多模块state指定类型
      • 登陆业务
        • 父组件调用子组件里面的方法
        • 登陆表单
        • 表单验证
        • 登陆逻辑
      • 权限业务
        • 动态路由
      • 小知识点
        • 如何传入组件的类型
        • json转ts类型
        • template里面使用路径别名
        • 文件夹目录扫描require.context
        • 错误
      • vue3模板
        • vuets
    • pinia状态管理
  • vuepress

  • hexo博客

  • 文档

  • biz业务

  • frontend
  • vue3
shollin
2022-03-11
目录

vue3-cms项目笔记

  • vue-cli搭建
  • 一、代码规范
    • 1.1. 集成editorconfig配置
    • 1.2. 使用prettier工具
    • 1.3. 使用ESLint检测
    • 1.4. git Husky和eslint
    • 1.5. git commit规范
  • 二、区分不同环境
  • 三. 第三方库集成
    • 2.1. vue.config.js配置
    • 2.2. vue-router集成
    • 2.3. vuex集成
    • 2.4. element-plus集成
    • 2.5. axios集成
    • 2.6. VSCode配置
  • 四. 接口文档
  • vuex
    • 给state给定类型
    • 多模块state指定类型
  • 登陆业务
    • 父组件调用子组件里面的方法
    • 登陆表单
  • 权限业务
    • 动态路由
  • 小知识点
    • 如何传入组件的类型
    • json转ts类型
    • template里面使用路径别名
    • 文件夹目录扫描require.context
  • vue3模板
    • vuets

# vue-cli搭建

vue create vue3-tpl
1

image-20220311163040713

# 一、代码规范

# 1.1. 集成editorconfig配置

EditorConfig 有助于为不同 IDE 编辑器上处理同一项目的多个开发人员维护一致的编码风格。

# http://editorconfig.org

root = true

[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
indent_style = space # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
end_of_line = lf # 控制换行类型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行首的任意空白字符
insert_final_newline = true # 始终在文件末尾插入一个新行

[*.md] # 表示仅 md 文件适用以下规则
max_line_length = off
insert_final_newline = false
trim_trailing_whitespace = false
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

VSCode需要安装一个插件:EditorConfig for VS Code

image-20210722215138665

vscode使用editorconfig插件以及.editorconfig配置文件说明详解_相关技巧_脚本之家 (jb51.net) (opens new window)

# 1.2. 使用prettier工具

Prettier 是一款强大的代码格式化工具,支持 JavaScript、TypeScript、CSS、SCSS、Less、JSX、Angular、Vue、GraphQL、JSON、Markdown 等语言,基本上前端能用到的文件格式它都可以搞定,是当下最流行的代码格式化工具。

1.安装prettier

npm install prettier -D
1

2.配置.prettierrc文件:

  • useTabs:使用tab缩进还是空格缩进,选择false;
  • tabWidth:tab是空格的情况下,是几个空格,选择2个;
  • printWidth:当行字符的长度,推荐80,也有人喜欢100或者120;
  • singleQuote:使用单引号还是双引号,选择true,使用单引号;
  • trailingComma:在多行输入的尾逗号是否添加,设置为 none, 可选 :"all", "es5" or "none";
  • semi:语句末尾是否要加分号,默认值true,选择false表示不加;
{
  "useTabs": false,
  "tabWidth": 2,
  "printWidth": 80,
  "singleQuote": true,
  "trailingComma": "none",
  "semi": false
}
1
2
3
4
5
6
7
8

3.创建.prettierignore忽略文件

/dist/*
.local
.output.js
/node_modules/**

**/*.svg
**/*.sh

/public/*
1
2
3
4
5
6
7
8
9

4.VSCode需要安装prettier的插件

image-20210722214543454

5.测试prettier是否生效

  • 测试一:在代码中保存代码;
  • 测试二:配置一次性修改的命令;

在package.json中配置一个scripts:

    "prettier": "prettier --write ."
1

# 1.3. 使用ESLint检测

1.在前面创建项目的时候,我们就选择了ESLint,所以Vue会默认帮助我们配置需要的ESLint环境。

2.VSCode需要安装ESLint插件:

image-20210722215933360

3.解决eslint和prettier冲突的问题:

安装插件:(vue在创建项目时,如果选择prettier,那么这两个插件会自动安装)

npm i eslint-plugin-prettier eslint-config-prettier -D
1

添加prettier插件:

  extends: [
    "plugin:vue/vue3-essential",
    "eslint:recommended"
  ],
1
2
3
4
  extends: [
    "plugin:vue/vue3-essential",
    "eslint:recommended",
    "@vue/typescript/recommended",
    "@vue/prettier",
    "@vue/prettier/@typescript-eslint",
    'plugin:prettier/recommended'
  ],
1
2
3
4
5
6
7
8

# 规则rules

  • "no-unused-vars":"off", 忽略未使用的变量
  • "@typescript-eslint/no-unused-vars": "off",
  • "no-debugger": "off", 关闭debugger模式
  • "vue/no-unused-components": "off" 忽略未使用的vue组件
  • "eslint-disable-next-line": "off" 忽略标签换行不是一个语法错误 off warn error

# 1.4. git Husky和eslint

虽然我们已经要求项目使用eslint了,但是不能保证组员提交代码之前都将eslint中的问题解决掉了:

  • 也就是我们希望保证代码仓库中的代码都是符合eslint规范的;

  • 那么我们需要在组员执行 git commit 命令的时候对其进行校验,如果不符合eslint规范,那么自动通过规范进行修复;

那么如何做到这一点呢?可以通过Husky工具:

  • husky是一个git hook工具,可以帮助我们触发git提交的各个阶段:pre-commit、commit-msg、pre-push

如何使用husky呢?

这里我们可以使用自动配置命令:

npx husky-init && npm install
1

这里会做三件事:

1.安装husky相关的依赖:

image-20210723112648927

2.在项目目录下创建 .husky 文件夹:

npx huksy install
1

image-20210723112719634

3.在package.json中添加一个脚本:

image-20210723112817691

接下来,我们需要去完成一个操作:在进行commit时,执行lint脚本:

image-20210723112932943

这个时候我们执行git commit的时候会自动对代码进行lint校验。

git add .
git commit -m '提交'
1
2

# 1.5. git commit规范

# 1.5.1. 代码提交风格

通常我们的git commit会按照统一的风格来提交,这样可以快速定位每次提交的内容,方便之后对版本进行控制。

但是如果每次手动来编写这些是比较麻烦的事情,我们可以使用一个工具:Commitizen

  • Commitizen 是一个帮助我们编写规范 commit message 的工具;

1.安装Commitizen

npm install commitizen -D
1

2.安装cz-conventional-changelog,并且初始化cz-conventional-changelog:

npx commitizen init cz-conventional-changelog --save-dev --save-exact
1

这个命令会帮助我们安装cz-conventional-changelog:

image-20210723145249096

并且在package.json中进行配置:

这个时候我们提交代码需要使用 npx cz:

  • 第一步是选择type,本次更新的类型
Type 作用
feat 新增特性 (feature)
fix 修复 Bug(bug fix)
docs 修改文档 (documentation)
style 代码格式修改(white-space, formatting, missing semi colons, etc)
refactor 代码重构(refactor)
perf 改善性能(A code change that improves performance)
test 测试(when adding missing tests)
build 变更项目构建或外部依赖(例如 scopes: webpack、gulp、npm 等)
ci 更改持续集成软件的配置文件和 package 中的 scripts 命令,例如 scopes: Travis, Circle 等
chore 变更构建流程或辅助工具(比如更改测试环境)
revert 代码回退
  • 第二步选择本次修改的范围(作用域)

image-20210723150147510

  • 第三步选择提交的信息

image-20210723150204780

  • 第四步提交详细的描述信息

image-20210723150223287

  • 第五步是否是一次重大的更改

image-20210723150322122

  • 第六步是否影响某个open issue

image-20210723150407822

我们也可以在scripts中构建一个命令来执行 cz:

image-20210723150526211

# 1.5.2. 代码提交验证

如果我们按照cz来规范了提交风格,但是依然有同事通过 git commit 按照不规范的格式提交应该怎么办呢?

  • 我们可以通过commitlint来限制提交;

1.安装 @commitlint/config-conventional 和 @commitlint/cli

npm i @commitlint/config-conventional @commitlint/cli -D
1

2.在根目录创建commitlint.config.js文件,配置commitlint

module.exports = {
  extends: ['@commitlint/config-conventional']
}
1
2
3

3.使用husky生成commit-msg文件,验证提交信息:

npx husky add .husky/commit-msg "npx --no-install commitlint --edit $1"
1

# 二、区分不同环境

在开发中,有时候我们需要根据不同的环境设置不同的环境变量,常见的有三种环境:

  • 开发环境:development;

  • 生产环境:production;

  • 测试环境:test;

n 如何区分环境变量呢?常见有三种方式:

  • 方式一:手动修改不同的变量;

  • 方式二:根据process.env.NODE_ENV的值进行区分;

  • 方式三:编写不同的环境变量配置文件.env.XXX;

  1. .env 和 .env.local 定义的环境变量会被全局引用,并会与其它环境变量合并
  2. 声明环境变量必须以 VUE_APP_ 开头,不然会被过滤掉
  3. 除了 VUE_APP_* 变量之外,在你的应用代码中始终可用的还有两个特殊的变量:NODE_ENV 和 BASE_URL

参考: 模式和环境变量 | Vue CLI (vuejs.org) (opens new window)

# 三. 第三方库集成

# 2.1. vue.config.js配置

vue.config.js有三种配置方式:

  • 方式一:直接通过CLI提供给我们的选项来配置:
    • 比如publicPath:配置应用程序部署的子目录(默认是 /,相当于部署在 https://www.my-app.com/);
    • 比如outputDir:修改输出的文件夹;
  • 方式二:通过configureWebpack修改webpack的配置:
    • 可以是一个对象,直接会被合并;
    • 可以是一个函数,会接收一个config,可以通过config来修改配置;
  • 方式三:通过chainWebpack修改webpack的配置:
    • 是一个函数,会接收一个基于 webpack-chain (opens new window) 的config对象,可以对配置进行修改;
const path = require('path')

module.exports = {
  // 1.配置方式一: CLI提供的属性
  outputDir: './build',
  publicPath: './',
  // 2.配置方式二: 和webpack属性完全一致, 最后会进行合并
  // configureWebpack: {
  //   resolve: {
  //     alias: {
  //       components: '@/components'
  //     }
  //   }
  // },
  // configureWebpack: (config) => {
  //   config.resolve.alias = {
  //     '@': path.resolve(__dirname, 'src'),
  //     components: '@/components'
  //   }
  // }
  // 3.配置方式三: 会替换掉
  chainWebpack: (config) => {
    config.resolve.alias
      .set('@', path.resolve(__dirname, 'src'))
      .set('components', '@/components')
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# 2.2. vue-router集成

安装vue-router的最新版本:

npm install vue-router@next
1

创建router对象:

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

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/main',
    component: () => import('../views/main/main.vue')
  },
  {
    path: '/login',
    component: () => import('../views/login/login.vue')
  }
]

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

export default router
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

安装router:

import router from './router'
createApp(App).use(router).mount('#app')
1
2

在App.vue中配置跳转:

<template>
  <div id="app">
    <router-link to="/login">登录</router-link>
    <router-link to="/main">首页</router-link>
    <router-view></router-view>
  </div>
</template>
1
2
3
4
5
6
7

# 2.3. vuex集成

安装vuex:

npm install vuex@next
1

创建store对象:

import { createStore } from 'vuex'

const store = createStore({
  state() {
    return {
      name: 'coderwhy'
    }
  }
})

export default store
1
2
3
4
5
6
7
8
9
10
11

安装store:

createApp(App).use(router).use(store).mount('#app')
1

在App.vue中使用:

<h2>{{ $store.state.name }}</h2>
1

# 2.4. element-plus集成

Element Plus (element-plus.org) (opens new window),一套为开发者、设计师和产品经理准备的基于 Vue 3.0 的桌面端组件库:

  • 相信很多同学在Vue2中都使用过element-ui,而element-plus正是element-ui针对于vue3开发的一个UI组件库;
  • 它的使用方式和很多其他的组件库是一样的,所以学会element-plus,其他类似于Ant Design Vue (antdv.com) (opens new window)、NaiveUI、Vant 3 - 轻量、可靠的移动端组件库 (opens new window)都是差不多的;

安装element-plus

npm install element-plus
1

# 2.4.1. 全局引入

一种引入element-plus的方式是全局引入,代表的含义是所有的组件和插件都会被自动注册:

import ElementPlus from 'element-plus'
//import 'element-plus/lib/theme-chalk/index.css'
import 'element-plus/dist/index.css'

import router from './router'
import store from './store'

createApp(App).use(router).use(store).use(ElementPlus).mount('#app')
1
2
3
4
5
6
7
8

# 2.4.2. 局部引入

也就是在开发中用到某个组件对某个组件进行引入:

<template>
  <div id="app">
    <router-link to="/login">登录</router-link>
    <router-link to="/main">首页</router-link>
    <router-view></router-view>

    <h2>{{ $store.state.name }}</h2>

    <el-button>默认按钮</el-button>
    <el-button type="primary">主要按钮</el-button>
    <el-button type="success">成功按钮</el-button>
    <el-button type="info">信息按钮</el-button>
    <el-button type="warning">警告按钮</el-button>
    <el-button type="danger">危险按钮</el-button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

import { ElButton } from 'element-plus'

export default defineComponent({
  name: 'App',
  components: {
    ElButton
  }
})
</script>

<style lang="less">
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

但是我们会发现是没有对应的样式的,引入样式有两种方式:

  • 全局引用样式(像之前做的那样);
  • 局部引用样式(通过babel的插件);

1.安装babel的插件:

npm install babel-plugin-import -D
1

2.配置babel.config.js

module.exports = {
  plugins: [
    [
      'import',
      {
        libraryName: 'element-plus',
        customStyleName: (name) => {
          return `element-plus/lib/theme-chalk/${name}.css`
        }
      }
    ]
  ],
  presets: ['@vue/cli-plugin-babel/preset']
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

这里还是需要引入基础样式 ``

但是这里依然有个弊端:

  • 这些组件我们在多个页面或者组件中使用的时候,都需要导入并且在components中进行注册;
  • 所以我们可以将它们在全局注册一次;
import {
  ElButton,
  ElTable,
  ElAlert,
  ElAside,
  ElAutocomplete,
  ElAvatar,
  ElBacktop,
  ElBadge,
} from 'element-plus'

const app = createApp(App)

const components = [
  ElButton,
  ElTable,
  ElAlert,
  ElAside,
  ElAutocomplete,
  ElAvatar,
  ElBacktop,
  ElBadge
]

for (const cpn of components) {
  app.component(cpn.name, cpn)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 2.5. axios集成

axios中文文档|axios中文网 | axios (axios-js.com) (opens new window)

httpbin.org测试接口 (opens new window)

安装axios:

npm install axios
1

# axios请求方式

支持多种请求方式:

  • axios(config)

  • axios.request(config)

  • axios.get(url[, config])

  • axios.delete(url[, config])

  • axios.head(url[, config])

  • axios.post(url[, data[, config]])

  • axios.put(url[, data[, config]])

  • axios.patch(url[, data[, config]])

有时候, 我们可能需求同时发送两个请求

  • 使用axios.all, 可以放入多个请求的数组.

  • axios.all([]) 返回的结果是一个数组,使用 axios.spread 可将数组 [res1,res2] 展开为 res1, res2

# axios的配置选项

请求地址

  • url: '/user',

请求类型

  • method: 'get',

请根路径

  • baseURL: 'http://www.mt.com/api',

请求前的数据处理

  • transformRequest:[function(data){}],

请求后的数据处理

  • transformResponse: [function(data){}],

自定义的请求头

  • headers:{'x-Requested-With':'XMLHttpRequest'},

URL查询对象

  • params:{ id: 12 },

查询对象序列化函数

  • paramsSerializer: function(params){ }

request body

  • data: { key: 'aa'},

超时设置s

  • timeout: 1000,

跨域是否带Token

  • withCredentials: false,

自定义请求处理

  • adapter: function(resolve, reject, config){},

身份验证信息

  • auth: { uname: '', pwd: '12'},

响应的数据格式 json / blob /document /arraybuffer / text / stream

  • responseType: 'json',

# axios的拦截器

为什么要创建axios的实例呢?

  • 当我们从axios模块中导入对象时, 使用的实例是默认的实例.

  • 当给该实例设置一些默认配置时, 这些配置就被固定下来了.

  • 但是后续开发中, 某些配置可能会不太一样.

  • 比如某些请求需要使用特定的baseURL或者timeout或者content-Type等.

  • 这个时候, 我们就可以创建新的实例, 并且传入属于该实例的配置信息.

axios的也可以设置拦截器:拦截每次请求和响应

  • axios.interceptors.request.use(请求成功拦截, 请求失败拦截)

  • axios.interceptors.response.use(响应成功拦截, 响应失败拦截)

image-20220315174518287

import axios from 'axios'

// axios的实例对象
// 1.模拟get请求
axios.get('http://123.207.32.32:8000/home/multidata').then((res) => {
  console.log(res.data)
})

// 2.get请求,并且传入参数
// axios
//   .get('http://httpbin.org/get', {
//     params: {
//       name: 'coderwhy',
//       age: 18
//     }
//   })
//   .then((res) => {
//     console.log(res.data)
//   })

// // 3.post请求
// axios
//   .post('http://httpbin.org/post', {
//     data: {
//       name: 'why',
//       age: 18
//     }
//   })
//   .then((res) => {
//     console.log(res.data)
//   })

// 额外补充的Promise中类型的使用
// Promise本身是可以有类型
// new Promise<string>((resolve) => {
//   resolve('abc')
// }).then((res) => {
//   console.log(res.length)
// })

// 4.axios的配置选项
// 4.1. 全局的配置
axios.defaults.baseURL = 'http://httpbin.org'
axios.defaults.timeout = 10000
// axios.defaults.headers = {}

// 4.2. 每一个请求单独的配置
// axios
//   .get('/get', {
//     params: {
//       name: 'coderwhy',
//       age: 18
//     },
//     timeout: 5000,
//     headers: {}
//   })
//   .then((res) => {
//     console.log(res.data)
//   })

// 3.post请求
// axios
//   .post('/post', {
//     data: {
//       name: 'why',
//       age: 18
//     }
//   })
//   .then((res) => {
//     console.log(res.data)
//   })

// 5.axios.all -> 多个请求, 一起返回
axios
  .all([
    axios.get('/get', { params: { name: 'why', age: 18 } }),
    axios.post('/post', { data: { name: 'why', age: 18 } })
  ])
  .then((res) => {
    console.log(res[0].data)
    console.log(res[1].data)
  })

// 6.axios的拦截器
// fn1: 请求发送成功会执行的函数
// fn2: 请求发送失败会执行的函数
axios.interceptors.request.use(
  (config) => {
    // 想做的一些操作
    // 1.给请求添加token
    // 2.isLoading动画
    console.log('请求成功的拦截')
    return config
  },
  (err) => {
    console.log('请求发送错误')
    return err
  }
)

// fn1: 数据响应成功(服务器正常的返回了数据 20x)
axios.interceptors.response.use(
  (res) => {
    console.log('响应成功的拦截')
    return res
  },
  (err) => {
    console.log('服务器响应失败')
    return err
  }
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

# 封装axios:

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { Result } from './types'
import { useUserStore } from '/@/store/modules/user'

class HYRequest {
  private instance: AxiosInstance

  private readonly options: AxiosRequestConfig

  constructor(options: AxiosRequestConfig) {
    this.options = options
    this.instance = axios.create(options)

    this.instance.interceptors.request.use(
      (config) => {
        const token = useUserStore().getToken
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }
        return config
      },
      (err) => {
        return err
      }
    )

    this.instance.interceptors.response.use(
      (res) => {
        // 拦截响应的数据
        if (res.data.code === 0) {
          return res.data.data
        }
        return res.data
      },
      (err) => {
        return err
      }
    )
  }

  request<T = any>(config: AxiosRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      this.instance
        .request<any, AxiosResponse<Result<T>>>(config)
        .then((res) => {
          resolve((res as unknown) as Promise<T>)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  get<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'GET' })
  }

  post<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'POST' })
  }

  patch<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'PATCH' })
  }

  delete<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request({ ...config, method: 'DELETE' })
  }
}

export default HYRequest
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

# 2.6. VSCode配置

{
  "workbench.iconTheme": "vscode-great-icons",
  "editor.fontSize": 17,
  "eslint.migration.2_x": "off",
  "[javascript]": {
    "editor.defaultFormatter": "dbaeumer.vscode-eslint"
  },
  "files.autoSave": "afterDelay",
  "editor.tabSize": 2,
  "terminal.integrated.fontSize": 16,
  "editor.renderWhitespace": "all",
  "editor.quickSuggestions": {
    "strings": true
  },
  "debug.console.fontSize": 15,
  "window.zoomLevel": 1,
  "emmet.includeLanguages": {
    "javascript": "javascriptreact"
  },
  "explorer.confirmDragAndDrop": false,
  "workbench.tree.indent": 16,
  "javascript.updateImportsOnFileMove.enabled": "always",
  "editor.wordWrap": "on",
  "path-intellisense.mappings": {
    "@": "${workspaceRoot}/src"
  },
  "hediet.vscode-drawio.local-storage": "eyIuZHJhd2lvLWNvbmZpZyI6IntcImxhbmd1YWdlXCI6XCJcIixcImN1c3RvbUZvbnRzXCI6W10sXCJsaWJyYXJpZXNcIjpcImdlbmVyYWw7YmFzaWM7YXJyb3dzMjtmbG93Y2hhcnQ7ZXI7c2l0ZW1hcDt1bWw7YnBtbjt3ZWJpY29uc1wiLFwiY3VzdG9tTGlicmFyaWVzXCI6W1wiTC5zY3JhdGNocGFkXCJdLFwicGx1Z2luc1wiOltdLFwicmVjZW50Q29sb3JzXCI6W1wiRkYwMDAwXCIsXCIwMENDNjZcIixcIm5vbmVcIixcIkNDRTVGRlwiLFwiNTI1MjUyXCIsXCJGRjMzMzNcIixcIjMzMzMzM1wiLFwiMzMwMDAwXCIsXCIwMENDQ0NcIixcIkZGNjZCM1wiLFwiRkZGRkZGMDBcIl0sXCJmb3JtYXRXaWR0aFwiOjI0MCxcImNyZWF0ZVRhcmdldFwiOmZhbHNlLFwicGFnZUZvcm1hdFwiOntcInhcIjowLFwieVwiOjAsXCJ3aWR0aFwiOjExNjksXCJoZWlnaHRcIjoxNjU0fSxcInNlYXJjaFwiOnRydWUsXCJzaG93U3RhcnRTY3JlZW5cIjp0cnVlLFwiZ3JpZENvbG9yXCI6XCIjZDBkMGQwXCIsXCJkYXJrR3JpZENvbG9yXCI6XCIjNmU2ZTZlXCIsXCJhdXRvc2F2ZVwiOnRydWUsXCJyZXNpemVJbWFnZXNcIjpudWxsLFwib3BlbkNvdW50ZXJcIjowLFwidmVyc2lvblwiOjE4LFwidW5pdFwiOjEsXCJpc1J1bGVyT25cIjpmYWxzZSxcInVpXCI6XCJcIn0ifQ==",
  "hediet.vscode-drawio.theme": "Kennedy",
  "editor.fontFamily": "Source Code Pro, 'Courier New', monospace",
  "editor.smoothScrolling": true,
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "workbench.colorTheme": "Atom One Dark",
  "vetur.completion.autoImport": false,
  "security.workspace.trust.untrustedFiles": "open",
  "eslint.lintTask.enable": true,
  "eslint.alwaysShowStatus": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

# 四. 接口文档

https://documenter.getpostman.com/view/12387168/TzsfmQvw

baseURL的值:

http://152.136.185.210:5000
1

设置全局token的方法:在登陆请求的Tests里面设置如下代码; 在要用token的地方,用指代就可以了

const res = pm.response.json();
pm.globals.set("token", res.data.token);
1
2

接口文档v2版本:(有部分更新)

https://documenter.getpostman.com/view/12387168/TzzDKb12

# vuex

# 给state给定类型

image-20220325092035536

image-20220325092258640

import { Module } from 'vuex'
const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
    }
  },
  getters: {},
  mutations: { },
  actions: {}
}
export default loginModule
1
2
3
4
5
6
7
8
9
10
11
12

# 多模块state指定类型

在多模块时,vuex的useStore不方便指定类型,可以自己封装一个类型,里面包含rootState和子模块state

import { createStore, Store, useStore as useVuexStore } from 'vuex'

import login from './login/login'

import { IRootState, IStoreType } from './types'

const store = createStore<IRootState>({
  state() {
    return {
      name: 'coderwhy',
      age: 18
    }
  },
  mutations: {},
  getters: {},
  actions: {},
  modules: {
    login
  }
})

export function setupStore() {
  store.dispatch('login/loadLocalLogin')
}

export function useStore(): Store<IStoreType> { // 返回自己封装的state类型
  return useVuexStore()
}

export default store
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { ILoginState } from './login/types'

export interface IRootState { // 根root
  name: string
  age: number
}

export interface IRootWithModule {
  login: ILoginState  // 子模块的state
}

export type IStoreType = IRootState & IRootWithModule
1
2
3
4
5
6
7
8
9
10
11
12

参考:

useStore | Vuex (vuejs.org) (opens new window)

# 登陆业务

# 父组件调用子组件里面的方法

如何获取子组件

1、定义ref属性<login-account ref="accountRef" />

2、ref()获取,名称一致即可,传入的类型为const accountRef = ref<InstanceType<typeof LoginAccount>>()

<template>
  <div class="login-panel">
    <h1 class="title">后台管理系统</h1>
    <el-tabs type="border-card" stretch v-model="currentTab">
      <el-tab-pane name="account">
        <template #label>
          <span><i class="el-icon-user-solid"></i> 账号登录</span>
        </template>
        <login-account ref="accountRef" />
      </el-tab-pane>
      <el-tab-pane name="phone">
        <template #label>
          <span><i class="el-icon-mobile-phone"></i> 手机登录</span>
        </template>
        <login-phone ref="phoneRef" />
      </el-tab-pane>
    </el-tabs>

    <div class="account-control">
      <el-checkbox v-model="isKeepPassword">记住密码</el-checkbox>
      <el-link type="primary">忘记密码</el-link>
    </div>

    <el-button type="primary" class="login-btn" @click="handleLoginClick"
      >立即登录</el-button
    >
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import LoginAccount from './login-account.vue'
import LoginPhone from './login-phone.vue'

export default defineComponent({
  components: {
    LoginAccount,
    LoginPhone
  },
  setup() {
    // 1.定义属性
    const isKeepPassword = ref(true)
    const accountRef = ref<InstanceType<typeof LoginAccount>>()
    const phoneRef = ref<InstanceType<typeof LoginPhone>>()
    const currentTab = ref('account')

    // 2.定义方法
    const handleLoginClick = () => {
      if (currentTab.value === 'account') {
        accountRef.value?.loginAction(isKeepPassword.value)
      } else {
        console.log('phoneRef调用loginAction')
      }
    }

    return {
      isKeepPassword,
      accountRef,
      phoneRef,
      currentTab,
      handleLoginClick
    }
  }
})
</script>

<style scoped lang="less">
.login-panel {
  margin-bottom: 150px;
  width: 320px;

  .title {
    text-align: center;
  }

  .account-control {
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
  }

  .login-btn {
    width: 100%;
    margin-top: 10px;
  }
}
</style>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

# 登陆表单

# 表单验证

# 登陆逻辑

1、登陆的逻辑(网络请求,拿到数据后的处理)

2、数据保存到某一个位置

3、发送其它的请求(如请求当前用户的信息)

4、拿到用户的菜单

5、跳到首页

  • 登陆后的数据如果保存在vuex当中,因为vuex数据是保存在内存里面的,如果页面刷新,vuex里面是没有数据的,这时,需要在项目启动的时候,就将本地缓存里面的数据加载到vuex里面
// 初始化store里面的数据: 加载本地缓存数据到store
export function initStore(){
  store.dispatch('login/loadLocalLogin');
}
1
2
3
4
<template>
  <div class="login-account">
    <el-form label-width="60px" :rules="rules" :model="account" ref="formRef">
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { ElForm } from 'element-plus'
import localCache from '@/utils/cache'

import { rules } from '../config/account-config'

export default defineComponent({
  setup() {
    const store = useStore()

    const account = reactive({
      name: localCache.getCache('name') ?? '',
      password: localCache.getCache('password') ?? ''
    })

    const formRef = ref<InstanceType<typeof ElForm>>()

    const loginAction = (isKeepPassword: boolean) => {
      formRef.value?.validate((valid) => {
        if (valid) {
          // 1.判断是否需要记住密码
          if (isKeepPassword) {
            // 本地缓存
            localCache.setCache('name', account.name)
            localCache.setCache('password', account.password)
          } else {
            localCache.deleteCache('name')
            localCache.deleteCache('password')
          }

          // 2.开始进行登录验证
          store.dispatch('login/accountLoginAction', { ...account })
        }
      })
    }

    return {
      account,
      rules,
      loginAction,
      formRef
    }
  }
})
</script>
<style scoped></style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

# 权限业务

# 动态路由

# 小知识点

# 如何传入组件的类型

在父组件要调用子组件里面的方法时,可以给组件加上ref属性, 但是子组件的类型不好定义,这时可以采用typeof来获取,如代码

<login-account ref="accountRef" />

//const accountRef = ref(); // 拿到ref属性值相同的组件,但是不知道组件的类型
const accountRef = ref<InstanceType<typeof LoginAccount>>()
// 2.定义方法
 const handleLoginClick = () => {
      if (currentTab.value === 'account') {
        accountRef.value?.loginAction(isKeepPassword.value) // 调用子组件里面的方法,因为传了组件类型,方法名是不会写错的
      } else {
        console.log('phoneRef调用loginAction')
      }
    }
1
2
3
4
5
6
7
8
9
10
11
12

见element-plus的源码 form.d.ts

参考:TypeScript: instancetype(typescriptlang.org) (opens new window)

# json转ts类型

在与后端交互时,后端传来的json数据,需要转成typescript相应的接口类型进行接收,可以采用工具json2ts - generate TypeScript interfaces from json (opens new window)

# template里面使用路径别名

<img class="img" src="~@/assets/img/logo.svg" alt="logo" />
1

# 文件夹目录扫描require.context

require.context为webpack提供的函数,接受三个参数

  1. directory {String} -读取文件的路径
  2. useSubdirectories {Boolean} -是否遍历文件的子目录
  3. regExp {RegExp} -匹配文件的正则
// 加载目录router/main下面,包括子目录里面所有的ts文件
const routeFiles = require.context('../router/main', true, /\.ts/)
routeFiles.keys().forEach((key) => {
    const route = require('../router/main' + key.split('.')[1])  //require加载文件
    allRoutes.push(route.default)
  })
1
2
3
4
5
6

使用require.context实现前端工程自动化 - 简书 (jianshu.com) (opens new window)

require.context 路由的模块化和统一管理_大盗夕落的博客-CSDN博客 (opens new window)

requirecontext Dependency Management | webpack (opens new window)

# 错误

webpack_require__(...).context is not a function

解决:注意require.context()里面直接写路径,如果用变量的话,会报错, 官方提醒:The arguments passed to require.context must be literals! literals翻译为字面量;文字的;逐字的;无夸张的

# vue3模板

# vuets

<template>
  <div class="home">
  
  </div>
</template>

<script lang="ts">
import { h, reactive, ref, watch,computed, onMounted, defineComponent } from 'vue'
import { useStore,createNamespacedHelpers } from 'vuex';
import { useRoute  } from 'vue-router';

  export default defineComponent({
    name: "HomeView",
    components: {},
    props: {  },
    setup() {
      return {
      
      };
    },
  });
</script>
<style scoped lang="less">

</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
vue开源项目
pinia状态管理

← vue开源项目 pinia状态管理→

最近更新
01
国际象棋
09-15
02
成语
09-15
03
自然拼读
09-15
更多文章>
Theme by Vdoing | Copyright © 2019-2023 zxpnet | 粤ICP备14079330号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式