基于Vue3 + Typescript 封装 Element-Plus 组件

1. 课程简介

项目地址 git clone https://gitee.com/childe-jia/my-message.git

背景: 该课程是基于Vue3 + Typescript + Vite构建, 教会大家封装Element-Plus组件

具备能力:

  • 最新的 Vue3 及相关技术
  • 组件的设计思想
  • 大厂的开发模式/代码规范

技术:

  • Vue3

    • 首次渲染 / diff 算法 更快

    • 内存占用 / 打包体积 更少

    • Composition API 组合 API
      在这里插入图片描述

      • Options API:基于对象的方式,将组件的各种选项,如data、methods、computed等,组织在一个对象中
      • Composition API:允许我们将组件的逻辑拆分成更小的、可复用的部分,从而实现更高度的组件复用。
  • Typescript

    • 介绍: 是一种带有 类型语法 的 JavaScript 语言,在任何使用 JavaScript 的开发场景中都可以使用。

      • JavaScript 代码
      // 没有明确的类型
      const age = 18
      
      • TypeScript 代码
      // 有明确的类型,可以指定age是number类型(数字类型)
      const age: number = 18
      
    • 作用: 编译时进行类型检查提示错误

      const num = 18;
      num.toLowerCase() 
      // Uncaught TypeError: num.toLowerCase is not a function
      

      这些错误导致在开发项目的时候,需要花挺多的时间去定位和处理 BUG

      原因:

      • JS 是动态类型的编程语言,动态类型最大的特点就是它只能在 代码执行 期间做类型的相关检查,所以往往你发现问题的时候,已经晚了。

      解决方案

      • TS 是静态类型的编程语言,代码会先进行编译然后去执行,在 代码编译 期间做类型的相关检查,如果有问题编译是不通过的,也就暴露出了问题。

      TS 优势

      • 更早发现错误,提高开发效率

      • 随时随地提示,增强开发体验

      • 强大类型系统,代码可维护性更好

  • Vite

    • 一种新型前端构建工具,能够显著提升前端开发体验

    • 对比 webpack

      • webpack构建原理

        • 需要查找依赖,打包所有的模块,然后才能提供服务,更新速度会随着代码体积增加越来越慢
          在这里插入图片描述
    • vite 的原理

      • 使用原生 ESModule 通过 script 标签动态导入,访问页面的时候加载到对应模块编译并响应

在这里插入图片描述

  • Vue3 + TS + Vite 最新的开发技术栈,你还在等什么…

2. 项目创建

掌握:使用 create-vue 脚手架创建项目

create-vue参考地址:https://github.com/vuejs/create-vue

  1. 执行创建命令:

    # pnpm
    pnpm create vue
    # npm
    npm init vue@latest
    # yarn
    yarn create vue
    
  2. 选择项目依赖内容

在这里插入图片描述

3. 组件需求分析

3.1 Message 消息提示 - 组件分析

功能分析

  • 常用于主动操作后的反馈提示
  • 提示在一定时间后可以消失
  • 可以手动关闭
  • 有多种类型 ( success warning error message)

难点

  • 使用函数式的方式来创建组件

    createMessage('hello Vue', props)
    // 如何将一个组件函数式的渲染到一个节点上?
    // 可以采用createApp?.....
    
    
    

类型属性分析

```typescript 
interface MessageProps {
    message?: stirng;
    duration?: number;
    showClose?: boolean;
    type?: 'primary' : 'success' : .... 
}

事件以及实例

const instance = createMessage('hello world', props)
instance.close()

事件以及实例

const instance = createMessage('hello world', props)
instance.close()

3.2 Message组件创建

  1. 创建目录

    • Message
      • style.css - 样式
      • Message.vue - 组件
      • method.ts - api方法
      • types.ts - 辅助的 typescript 类型

    报错:

    Component name “Message” should always be multi-word

    原因:

    要求组件名称以驼峰格式命名, 自定义组件名称应该由多个单词组成, 防止和html标签冲突, 所以会报错

    解决:

    .eslintrc.js

      rules: {
        // 关闭组件命名规则
        'vue/multi-word-component-names': 'off'
      }
    
  2. 编写组件

Message.vue

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import type { MessageProps } from './types'
const visible = ref(false)

const props = withDefaults(defineProps<MessageProps>(), {
  duration: 3000,
  type: 'message'
})
function startTimer() {
  if (props.duration === 0) return
  setTimeout(() => {
    visible.value = false
  }, props.duration);
}

onMounted(() => {
  visible.value = true
  startTimer()
})
</script>

<template>
  <div class="message-box" v-show="visible">
    <div class="message_content">
      <span>{{ message }}</span>
    </div>
      <img v-if="showClose" @click="visible = false" src="./close1.png" alt="">
  </div>
</template>

<style scoped>
.message-box {
  width: max-content;
  position: fixed;
  left: 50%;
  top: 20px;
  transform: translateX(-50%);
  border: 1px solid skyblue;
}
</style>

types.ts

interface MessageProps {
    message?: stirng;
    duration?: number;
    showClose?: boolean;
    type?: 'primary' : 'success' : .... 
}

App.vue

import Message from './components/Message/Message.vue'

<Message message="hello vue" :duration="0"></Message>

3.4 将组件Render到DOM节点上

使用createApp 的弊端

  • 该方法太重了, 它返回的是一个应用的实例, 而我们这里只需要轻量级的解决方法

  • 隆重介绍render 函数

    // 它负责将一个vnode渲染到dom节点上
    // 它是一个轻量级的解决方案
    import { render } from 'vue'
    render(vNode, DOM节点)
    

method.ts

import MessageConstructor from "./Message.vue";
import type { MessageProps } from "./types";
import { render, h } from 'vue'
export  const createMessage = (props: MessageProps) => {
  const container = document.createElement('div')
  const vnode = h(MessageConstructor, props)
  render(vnode, container)
  document.body.appendChild(container.firstElementChild!)
}

App.vue

// import Message from './components/Message/Message.vue'

createMessage({ message: 'hello vue', duration: 0 })

3.5 移除节点

method.ts

// import MessageConstructor from "./Message.vue";
-- import type { MessageProps } from "./types";
++ import type { CreateMessageProps } from "./types";
// import { render, h } from 'vue'
++ export const createMessage = (props: CreateMessageProps) => {
//   const container = document.createElement('div')
++ const destroy = () => {
++    render(null, container)
++  }
++  const newProps = {
++    ...props,
++    onDestroy: destroy
++  }
++  const vnode = h(MessageConstructor, newProps)
  render(vnode, container)
  document.body.appendChild(container.firstElementChild!)
}

types.ts

export interface MessageProps {
 // ....
++ onDestroy: () => void
}

++ export type CreateMessageProps = Omit<MessageProps, 'onDestroy'>

Message.vue

<script setup lang="ts">
// ....
++ watch(visible, (newValue) => {
++  if (!newValue) {
++    props.onDestroy()
++  }
++ })
<script/>

3.6 获取上一个组件实例

types.ts

import type { VNode } from "vue";
export interface MessageContext {
  id: string;
  vnode: VNode;
  props: MessageProps
}

method.ts

++ import type { CreateMessageProps, MessageContext } from "./types";
++ const instances: MessageContext[] = []
++ let seed = 1
export  const createMessage = (props: CreateMessageProps) => {
++  const id = `message_${seed++}`
  const destroy = () => {
++    const idx = instances.findIndex(instance => instance.id === id)
++    if (idx === -1) return 
++    instances.splice(idx, 1)
    render(null, container)
  }
// ....
  document.body.appendChild(container.firstElementChild!)
++  const instance = {
++    id,
++    vnode,
++    props: newProps
++  }
++  instances.push(instance)
++  return instance
}

++ export const getLastInstance = () => {
++  return instances[instances.length - 1]
++ }

Message.vue

import { getLastInstance } from './method'

const prevInstance = getLastInstance()
console.log('prevInstance', prevInstance);

3.7 动态计算组件位置

在这里插入图片描述
method.ts

// 伪方法: 获取上一个实例的最下面的坐标数字
export const getLastBottomOffset = () => {
  return 0
}

types.ts

export interface MessageProps {
  // ***	
++  offset?: number
}

Message.vue

<script setup lang="ts">
++ import {  nextTick } from 'vue';
++ import {  getLastBottomOffset } from './method'
const visible = ref(false)

const props = withDefaults(defineProps<MessageProps>(), {
  duration: 3000,
  type: 'message',
++  offset: 20
})
// const prevInstance = getLastInstance()
// console.log('prevInstance', prevInstance);
++ const messageRef = ref<HTMLDivElement>()
// 计算偏移高度
// div的高度
++ const height = ref(0)
// 上一个实例的最下面的坐标数字, 是0
++ const lastOffset = computed(() => getLastBottomOffset())
// 该元素的top计算值
++ const topOffset = computed(() => lastOffset.value + props.offset)
// 这个元素为下一个元素预留的offset, 也就是它最低端的bottom的值
++ const bottomOffset = computed(() => height.value + topOffset.value)
++ const cssStyle = computed(() => ({
++   top: topOffset.value + 'px'
++ }))
++  onMounted(async () => {
  visible.value = true
  startTimer()
++   await nextTick()
++   height.value = messageRef.value!.getBoundingClientRect().height
})
watch(visible, (newValue) => {
  if (!newValue) {
    props.onDestroy()
  }
})
++ 当然bottomOffset要给下一个组件使用, 所以说需要暴露出去
++ defineExpose({
++   bottomOffset
++ })
</script>
++ div class="message-box" :style="cssStyle" ref="messageRef" v-show="visible">

3.8 获取bottomOffset

types.ts

++1111 import type { ComponentInternalInstance } from 'vue'
export interface MessageProps {
  // xxx
++33333  id: string
}
export interface MessageContext {
 // xxx
++11111  vm: ComponentInternalInstance
}
++ 3333 export type CreateMessageProps = Omit<MessageProps, 'onDestroy'| 'id'>

method.ts

export  const createMessage = (props: CreateMessageProps) => {
 //  ...
  const newProps = {
     // xx
++  id
  }
  const vnode = h(MessageConstructor, newProps)
+++1111 console.log('vnode', vnode);
  
  render(vnode, container)
  document.body.appendChild(container.firstElementChild!)
++ 2222  const vm = vnode.component!
  const instance = {
    // xxx
++ 2222   vm
  }
}
// 获取上一个实例的最下面的坐标数字
++ 33333 export const getLastBottomOffset = (id: string) => {
++      const idx = instances.findIndex(instance => instance.id === id)
++     if (idx <= 0) {
++      return 0
++     } else {
++      const prev = instances[idx -1]
++      return prev.vm.exposed!.bottomOffset.value
  }
}

Message.vue

++ 3333 const lastOffset = computed(() => getLastBottomOffset(props.id))

<template>
++ 3333 <div class="message_content">
++      {{ offset }} {{ topOffset }} {{ height }} {{ bottomOffset }} <br>
++      <span>{{ message }}</span>
++ </div>	
</template>

3.9 解决Message重叠问题

method.ts

++ const instances: MessageContext[] = reactive([])

export const getLastBottomOffset = (id: string) => {
  const idx = instances.findIndex(instance => instance.id === id)
++  console.log('idx', id, idx, instances.length);
}

3.10 给组件实例添加删除方法

App.vue

onMounted(() => {
++  const instance = createMessage({ message: 'hello vue1', duration: 0 })
++  setTimeout(() => {
++    instance.destroy()
++  }, 2000);
})

meesage.vue

defineExpose({
  bottomOffset,
++  visible
})

method.ts

export  const createMessage = (props: CreateMessageProps) => {
++  const manuallyDestroy = () => {
++    const instance = instances.find(instance => instance.id === id)
++    if (instance) {
++      instance.vm.exposed!.visible.value = false
++    }
++  }

  const instance = {
    vm,
++  destroy: manuallyDestroy
  }
  instances.push(instance)
  return instance
}

types.ts

export interface MessageContext {
 // xxx 
++  destroy: () => void
}

3.11 添加样式

Message.vue

<div class="message-box" :class="{ [`el-message--${type}`]: type }" :style="cssStyle">

styles/vars.css

:root {
  /* message */
  --el-color-info-light-8: #e9e9eb;
  --el-color-info-light-9: #f4f4f5;
  /* success */
  --el-color-success: #67c23a;
  --el-color-success-light-8: #e1f3d8;
  --el-color-success-light-9: #f0f9eb;
  /* warning */
  --el-color-warning: #e6a23c;
  --el-color-warning-light-8: #faecd8;
  --el-color-warning-light-9: #fdf6ec;
  /* error */
  --el-color-error: #f56c6c;
  --el-color-error-light-8: #fde2e2;
  --el-color-error-light-9: #fef0f0;
}

styles/index.css

@import './vars.css';
@import '../components/Message/style.css';

Message/style.css

.message-box {
  width: max-content;
  position: fixed;
  left: 50%;
  top: 20px;
  transform: translateX(-50%);
  box-sizing: border-box;
  padding: 10px;
  display: flex;
  align-items: center;
  border-radius: 3px;

  border-color: var(--el-message-border-color);
  background-color: var(--el-message-bg-color);
  color: var(--el-message-text-color);
}
/* success */
.el-message--success {
  --el-message-bg-color: var(--el-color-success-light-9);
  --el-message-border-color: var(--el-color-success-light-8);
  --el-message-text-color: var(--el-color-success);
}
/* error */
.el-message--error {
  --el-message-bg-color: var(--el-color-error-light-9);
  --el-message-border-color: var(--el-color-error-light-8);
  --el-message-text-color: var(--el-color-error);
}
/* warning */
.el-message--warning {
  --el-message-bg-color: var(--el-color-warning-light-9);
  --el-message-border-color: var(--el-color-warning-light-8);
  --el-message-text-color: var(--el-color-warning);
}
/* message */
.el-message--message {
  --el-message-bg-color: var(--el-color-info-light-9);
  --el-message-border-color: var(--el-color-info-light-8);
}

main.ts

import { createApp } from 'vue'
import App from './App.vue'
++ import './styles/index.css'
createApp(App).mount('#app')

3.12 总结

  • 了解最新的 Vue3 及相关技术 & 优势

  • 具备经典组件的设计与开发,提升架构思维和代码设计能力

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/759282.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

5-linux文件路径与文件目录系统

目录 ①文件路径 目录跳转 绝对路径与相对路径 ②文件目录系统 目录系统组成 目录命名规则 命令补充 ls命令补充 file filename查看文件类型 less查看文本文件 ①文件路径 目录跳转 pwd:查看当前工作目录。 cd:改变目录。 ls:列出目录内容。 [root########## ~]# …

取证工作:怎样解锁 LUKS2 加密磁盘?

对于 LUKS2 密码进行恢复&#xff0c;Elcomsoft Distributed Password Recovery &#xff08;简称 EDPR&#xff09; 软件可以构建高性能集群&#xff0c;以更快地破解密码。EDPR 软件提供零开销的可扩展性&#xff0c;并支持 GPU 加速&#xff0c;以加快恢复速度。EDPR 可帮助…

下属无执行力,领导无能为力?用好这3大法则,打造一流行动力

下属无执行力&#xff0c;领导无能为力&#xff1f;用好这3大法则&#xff0c;打造一流行动力 第一个&#xff1a;漏斗法则 在沟通这个领域&#xff0c;有一个漏斗法则&#xff0c;意思就是指&#xff1a;如果你脑袋里面想表达的是100%&#xff0c;那你说出口的会只有80%&…

开发板以电脑为跳板连接互联网

标题 开发板以电脑为跳板连接互联网网络共享方式桥接方式 开发板以电脑为跳板连接互联网 分享下用网线直连电脑的开发板如何以电脑为跳板连接互联网的两个方法。 网络共享方式桥接方式 补充下&#xff0c;我的电脑连接的是无线网络&#xff0c;开发板和电脑是用网线进行连接的…

AI奏响未来乐章:音乐界的革命性变革

AI在创造还是毁掉音乐 引言 随着科技的飞速发展&#xff0c;人工智能&#xff08;AI&#xff09;正在逐渐渗透到我们生活的每一个角落&#xff0c;音乐领域也不例外。AI技术的引入&#xff0c;不仅为音乐创作、教育、体验带来了革命性的变革&#xff0c;更为整个音乐产业注入了…

昇思25天学习打卡营第7天|模型训练

模型训练 模型训练一般分为四个步骤&#xff1a; 构建数据集。定义神经网络模型。定义超参、损失函数及优化器。输入数据集进行训练与评估。 前面几天依次学习了前面几个步骤的操作&#xff0c;今天继续学习模型训练。 数据集和神经网络模型这个前面已经有详细的介绍。准确…

生成式AI如何赋能教育?商汤发布《2024生成式AI赋能教育未来》白皮书

生成式AI正在各个行业中展现出巨大的应用前景。在关系国计民生的教育行业&#xff0c;生成式AI能够催生哪些创新模式&#xff1f; 6月28日&#xff0c;商汤科技受邀参加2024中国AIGC应用与发展峰会&#xff0c;并在会上发布《2024生成式AI赋能教育未来》白皮书&#xff0c;提出…

Qt:5.QWidget属性介绍(isEnabled和geometry)

目录 一、 QWidget属性的介绍&#xff1a; 二、Enabled属性&#xff1a; 2.1Enabled属性的介绍&#xff1a; 2.2获取控件当前可用状态的api——isEnabled()&#xff1a; 2.3设置控件当前的可用状态的api—— setEnabled() &#xff1a; 2.4 实例&#xff1a;通过一个按钮&…

【人工智能学习之图像操作(六)】

【人工智能学习之图像操作&#xff08;六&#xff09;】 Hough变换直线检测圆检测 图像分割 Hough变换 在图像处理中&#xff0c;霍夫变换用来检测任意能够用数学公式表达的形状&#xff0c;即使这个形状被破坏或者有点扭曲 直线检测 import cv2 import numpy as np image …

Python 基础:用 json 模块存储和读取数据

目录 一、用 json 存储数据二、用 json 读取数据 遇到看不明白的地方&#xff0c;欢迎在评论中留言呐&#xff0c;一起讨论&#xff0c;一起进步&#xff01; 本文参考&#xff1a;《Python编程&#xff1a;从入门到实践&#xff08;第2版&#xff09;》 用户关闭程序时&#…

Redux实现Token持久化

业务背景: Token数据具有一定的时效时间&#xff0c;通常在几个小时&#xff0c;有效时间内无需重新获取&#xff0c;而基于Redux的存储方式又是基于内存的&#xff0c;刷新就会丢失&#xff0c;为了保持持久化&#xff0c;我们需要单独做处理 解决方案&#xff1a; 使用redu…

HTML图片链接缓存问题解决

关于解决HTML使用图片链接出现的缓存问题处理 1、项目上明明替换了图片却没发现更新&#xff0c;得去浏览器设置清除浏览器缓存或者其它一些操作才能解决&#xff0c;这也太麻烦了&#xff01;加载过一次不会再加载第二次&#xff0c;其实这时候就存在浏览器图片缓存情况&…

1-5题查询 - 高频 SQL 50 题基础版

目录 1. 相关知识点2. 例题2.1.可回收且低脂的产品2.2.寻找用户推荐人2.3.大的国家2.4. 文章浏览 I2.5. 无效的推文 1. 相关知识点 sql判断&#xff0c;不包含null&#xff0c;判断不出来distinct是通过查询的结果来去除重复记录ASC升序计算字符长度 CHAR_LENGTH() 或 LENGTH(…

cpu,缓存,辅存,主存之间的关系及特点

关系图 示意图&#xff1a; ------------------- | CPU | | ------------- | | | 寄存器 | | | ------------- | | | L1缓存 | | | ------------- | | | L2缓存 | | | ------------- | | | L3缓存 | | | ------------- | ----…

2095.删除链表的中间节点

给你一个链表的头节点 head 。删除链表的中间节点 &#xff0c;并返回修改后的链表的头节点 head。 长度为 n 链表的中间节点是从头数起第 ⌊n / 2⌋ 个节点&#xff08;下标从 0 开始&#xff09;&#xff0c;其中 ⌊x⌋ 表示小于或等于 x 的最大整数。 对于 n 1、2、3、4 和…

深入理解 Spring MVC:原理与架构解析

文章目录 前言一、MVC二、Spring MVC三、Spring MVC 工作流程四、小结推荐阅读 前言 Spring MVC 是一种基于 Java 的 Web 应用开发框架&#xff0c;它通过模型-视图-控制器&#xff08;Model-View-Controller, MVC&#xff09;的设计模式来组织和管理 Web 应用程序。本文将深入…

树莓派3B读写EEPROM芯片AT24C256

AT24C256是一个Atmel公司的EEPROM存储芯片&#xff0c;容量是256K个bit&#xff08;也就是32K字节&#xff09;&#xff0c;I2C接口&#xff0c;而树莓派正好有I2C接口&#xff0c;如下图蓝框中的4个IO口&#xff0c; 把AT24C256和这4个口接在一起&#xff0c;这样硬件就准备好…

Nginx的11个执行阶段

Nginx的11个执行阶段

ARCGIS添加在线地图

地图服务地址&#xff1a;http://map.geoq.cn/ArcGIS/rest/services 具体方法&#xff1a; 结果展示&#xff1a;

Spring底层原理之bean的加载方式八 BeanDefinitionRegistryPostProcessor注解

BeanDefinitionRegistryPostProcessor注解 这种方式和第七种比较像 要实现两个方法 第一个方法是实现工厂 第二个方法叫后处理bean注册 package com.bigdata1421.bean;import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.…