vue3 Element UI使用自定义内容

这里以Vue3版本的Element UI 举例

这是一个通知组件

在这里插入图片描述

通知的内容我们可以通过message参数来控制

例如:

<template>
  <el-button plain @click="open1">打开</el-button>
</template>

<script>
import { ElNotification } from "element-plus";

export default {
  name: "Demo",
  setup() {
    const open = () => {
      ElNotification.success({
          title: '成功',
          message: '这是一条成功的提示消息',
          type: 'success'
      });
    };
    return { open };
  }
};
</script>

期望效果

现在我们想要在这个通知栏中增加一个按钮,效果如下:

在这里插入图片描述

那么就需要在message字段中提供一个VNode,也就是组件的render函数

实现

首先通过resolveComponent 解析el-button然后,用h函数创建VNode赋值就可以实现。

<template>
    <el-button plain @click="open"> 打开 </el-button>
</template>

<script>
import { ElNotification } from "element-plus";
import { h, resolveComponent } from "vue";

export default {
  name: "Demo",
  setup(prorps, context) {
    const btn =resolveComponent("el-button");
    const open = () => {
      ElNotification.success({
        title: "Info",
        message: h(btn,{}, "应用"),
      });
    };
    return { open };
  }
};
</script>

VUE 2 vs VUE 3

vue2中渲染函数大致如下,并且可以直接通过 组件名称 直接创建已经注册的子组件。

// Vue 2 渲染函数示例
export default {
  render(h) {
    return h('div',{
  		staticClass: 'button',
  		class: { 'is-outlined': isOutlined },
  		staticStyle: { color: '#34495E' },
  		style: { backgroundColor: buttonColor },
  		attrs: { id: 'submit' },
  		domProps: { innerHTML: '' },
  		on: { click: submitForm },
 		key: 'submit-button'
		}, "子元素")
  }
}

Vue3修改为了实现 响应式API 调整 渲染函数 API ,与Vue2不兼容了。

Vue3中元素创建的函数被需要单独导入,创建元素的属性配置也变得扁平,并且无法直接创建已经注册的子组件,需要resolveComponent手动解析,然后创建。

import { h } from "vue";

const vNode = h('div',{
  						class: ['button', { 'is-outlined': isOutlined }],
  						style: [{ color: '#34495E' }, { backgroundColor: buttonColor }],
  						id: 'submit',
  						innerHTML: '',
  						onClick: submitForm,
  						key: 'submit-button'
					}, "子元素");

更多参考 VUE 官方 渲染函数 API

参考文献

  1. vuejs . 渲染函数 API . https://v3.cn.vuejs.org/guide/migration/render-function-api.html
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值