Vue3自定义指令实践:使用h函数渲染自定义组件到指令中

开发 前端
为了可以应对更多场景,我们期望可以配置加载中的提示信息,不配置使用默认值,如果是 false ,那么仅展示 loading 图。

🚀 关键接口介绍

最近想体验下自定义指令功能,看了看文档和 vue2 差异不大,语法如下:

const myDirective = {
// 在绑定元素的 attribute 前 
// 或事件监听器应用前调用
created(el, binding, vnode, prevVnode) 
{ // 下面会介绍各个参数的细节 }, 
// 在元素被插入到 DOM 前调用
beforeMount(el, binding, vnode, prevVnode) {},
// 在绑定元素的父组件
// 及他自己的所有子节点都挂载完成后调用
mounted(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件更新前调用
beforeUpdate(el, binding, vnode, prevVnode) {},
// 在绑定元素的父组件
// 及他自己的所有子节点都更新后调用
updated(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件卸载前调用
beforeUnmount(el, binding, vnode, prevVnode) {},
// 绑定元素的父组件卸载后调用
unmounted(el, binding, vnode, prevVnode) {}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

起初,最大的痛点是需要手动创建 dom ,然后插入 el 中。

const loadingDom = document.createElement('div', {calss: 'loading'})
el.append(loadingDom)
  • 1.
  • 2.

这样好难受啊,我不想写原生 dom ,能不能写个组件渲染到指令里呢?

我想起了我之前看到的几个 vue 接口,

  • h函数,也就是 vue 提供的创建 vNode 的函数
  • render函数:将 vNode 渲染到 真实 dom 里的函数

h函数用法如下:

// 完整参数签名
function h(
    type: string | Component,
    props?: object | null,
    children?: Children | Slot | Slots
): VNode
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

例如:

import { h } from 'vue'

const vnode = h('div', { class: 'container' }, [
  h('h1', 'Hello, Vue 3'),
  h('p', 'This is a paragraph')
])
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

我们使用h函数创建了一个 VNode,它表示一个包含 div、h1、p 的 DOM 结构。其中,div 的 class 属性为 container

🚀 自定义 loading 组件

然而,当我使用 props 为组件传递值时,发现是徒劳的。

import Loading from './components/Loading.vue';

cconst option = {
    msg: '一大波僵尸来袭',
    loading: true
}

const vnode = h(
    Loading,
    { id: 'loading', ...option}
)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

仅仅如下图一样,我以为是给组件的 props,实际上是 dom 的 props。

图片图片

此时我们的组件只能通过 $attrs 来获取这些 props 了,如下:

<template>

  <div class="loading">
    <div></div>
    <span v-if="$attrs.msg !== false">{{ $attrs.msg }}</span>
  </div>
  
</template>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

接着我们给组件实现 loading 动画,当然你也可以直接使用组件库的 loading 组件。

我的实现如下:

<style>
  @keyframes identifier {
    100% {
      -webkit-transform: rotate(360deg);
      transform: rotate(360deg);
    }
  }
  .loading {
    height: 100px;
    width: 100%;
  }
  .loading div {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    border: 2px solid green;
    margin: 25px auto;
    border-top: none;
    border-left: none;
    animation: identifier 1s infinite linear;
  }
</style>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

🚀 自定义指令

接下来我们封装自定义指令。

我们的思路是:

  • mounted 阶段,如果是 true,那么渲染组件,否则什么都不做。
  • update 阶段,如果 true 则重新渲染组件,如果 false 则渲染 vnode

为了可以应对更多场景,我们期望可以配置加载中的提示信息,不配置使用默认值,如果是 false ,那么仅展示 loading 图。所以参数类型如下:

interface Props  {loading: boolean, msg?: string | false}

v-loading: boolean | Props
  • 1.
  • 2.
  • 3.

由于可能是布尔值,也可能是对象,我们需要初始化配置参数

function formatOption (value: boolean | Props) {
  const loading = typeof value === 'boolean'
      ? value 
      : value.loading
  const option = typeof value !== 'boolean'
    ? Object.assign(defaultOption, value)
    : {
      loading,
      ...defaultOption
    }
  return { loading, option }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

接着再 mounted 阶段获取格式化后的 loading 和 option,如果为 true 则直接渲染组件。

const vLoading: Directive<HTMLElement, boolean | Props> = {
  mounted(el, binding) {

    const { loading, option } = formatOption(binding.value)

    loading && renderLoading(el, option)

  }
}

function renderLoading (el: HTMLElement, option: Props) {
  const vnode = h(
    Loading,
    { id: 'loading', ...option}
  )
  el.removeChild(el.children[0])
  render(vnode, el)
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

如果进入 update 阶段,则根据情况选择渲染 laoding 组件还是 vnode。

const vLoading: Directive<HTMLElement, boolean | Props> = {
  mounted(el, binding) {

    const { loading, option } = formatOption(binding.value)

    loading && renderLoading(el, option)

  },
  updated(el: HTMLElement, binding, vnode) {

    const { loading, option } = formatOption(binding.value)

    if (loading) {
      renderLoading(el, option)
    } else {
      renderVNode(el, vnode)
    }

  },
}

function renderLoading (el: HTMLElement, option: Props) {
  const vnode = h(
    Loading,
    { id: 'loading', ...option}
  )
  el.removeChild(el.children[0])
  render(vnode, el)
}

function renderVNode (el: HTMLElement, vnode: VNode) {
  el.querySelector('#loading')?.remove()
  render(vnode, el)
}
  • 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.

我们验证下功能:

  • 默认功能
const loading = ref(true)

setTimeout(() => loading.value = false, 2000)

</script>

<template>
  <div style="width: 300px" v-loading=laoding>
    <h1>加载成功</h1>
  </div>
</template>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

图片图片

  • 自定义文本
<template>
  <div style="width: 300px" v-loading="{ loading, msg: '一大波僵尸来袭' }">
    <h1>加载成功</h1>
  </div>
</template>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

图片图片

  • 不展示文本
<template>
  <div style="width: 300px" v-loading="{ loading, msg: false }">
    <h1>加载成功</h1>
  </div>
</template>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

图片图片

🎉 最后

今天的分享就到这了,如果有问题,可以评论区告诉我,我会及时更正。

以下是完整的代码。

<template>

  <div class="loading">
    <div></div>
    <span v-if="$attrs.msg !== false">{{ $attrs.msg }}</span>
  </div>
  
</template>
  
<script lang="ts">
export default {  
}
</script>
  
<style>
  @keyframes identifier {
    100% {
      -webkit-transform: rotate(360deg);
      transform: rotate(360deg);
    }
  }
  .loading {
    height: 100px;
    width: 100%;
  }
  .loading div {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    border: 2px solid green;
    margin: 25px auto;
    border-top: none;
    border-left: none;
    animation: identifier 1s infinite linear;
  }
</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.
<script setup lang="ts">
import { Directive, VNode, h, ref, render  } from 'vue';
import Loading from './components/Loading.vue';

const defaultOption: {msg?: string | false} = {
  msg: '努力加载中'
}

interface Props  {loading: boolean, msg?: string | false}

function formatOption (value: boolean | Props) {
  const loading = typeof value === 'boolean'
      ? value 
      : value.loading
  const option = typeof value !== 'boolean'
    ? Object.assign(defaultOption, value)
    : {
      loading,
      ...defaultOption
    }
  return { loading, option }
}

function renderLoading (el: HTMLElement, option: Props) {
  const vnode = h(
    Loading,
    { id: 'loading', ...option}
  )
  el.removeChild(el.children[0])
  render(vnode, el)
}

function renderVNode (el: HTMLElement, vnode: VNode) {
  el.querySelector('#loading')?.remove()
  render(vnode, el)
}

const vLoading: Directive<HTMLElement, boolean | Props> = {
  mounted(el, binding) {

    const { loading, option } = formatOption(binding.value)

    loading && renderLoading(el, option)

  },
  updated(el: HTMLElement, binding, vnode) {

    const { loading, option } = formatOption(binding.value)

    if (loading) {
      renderLoading(el, option)
    } else {
      renderVNode(el, vnode)
    }

  },
}

const loading = ref(true)

setTimeout(() => loading.value = false, 2000)

</script>

<template>
  <div style="width: 300px" v-loading="{ loading, msg: '一大波僵尸来袭' }">
    <h1>加载成功</h1>
  </div>
</template>
  • 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.

责任编辑:武晓燕 来源: 萌萌哒草头将军
相关推荐

2021-11-30 08:19:43

Vue3 插件Vue应用

2022-07-26 01:06:18

Vue3自定义指令

2021-07-05 15:35:47

Vue前端代码

2022-02-22 13:14:30

Vue自定义指令注册

2023-07-21 19:16:59

OpenAIChatGPT

2020-12-28 10:10:04

Vue自定义指令前端

2024-09-26 14:16:07

2022-08-01 11:41:00

Vue插件

2010-10-25 16:05:07

oracle自定义函数

2022-04-24 15:17:56

鸿蒙操作系统

2010-09-14 16:47:23

SQL自定义函数

2010-05-11 13:16:21

Unix awk

2017-05-18 12:36:16

android万能适配器列表视图

2015-02-12 15:33:43

微信SDK

2023-12-21 09:00:21

函数React 组件useEffect

2017-05-19 10:03:31

AndroidBaseAdapter实践

2009-06-24 15:13:36

自定义JSF组件

2023-02-20 15:20:43

启动页组件鸿蒙

2021-12-24 15:46:23

鸿蒙HarmonyOS应用

2024-06-03 10:00:51

Vue 3语法插槽
点赞
收藏

51CTO技术栈公众号