【前端开发】如何将vue组件转成自定义指令使用,(在自定义指令中使用element ui组件或常用组件方式)。
// 导入组件 import Vue from 'vue' import XxTips from 'packages/basic/xx-tips/src/XxTips.vue'
// 自定义指令 Vue.directive('tip', { bind(el, binding) { el.style.position = 'relative' console.log(el.getAttribute('class'), 'el')
// 引入组件 const TagItemClass = Vue.extend(XxTips) const { schema, term, module, position, tipsData } = binding.value let domType = '' const domClass = el.getAttribute('class') if (domClass && domClass.includes('el-input')) { domType = 'input' } else if (domClass && domClass.includes('el-button')) { domType = 'button' } else { domType = 'table' } const tagItemInstance = new TagItemClass({
// 给组件传参 propsData: { schema, term, tipsType: domType, module, position, tipsData, }, }).$mount() // tagItemInstance.$el.setAttribute('contenteditable', false)
// 将引入的组件动态插入所在dom后面
el.appendChild(tagItemInstance.$el) }, })
使用方式
<el-input
placeholder="请输入"
v-tip="{
term: 'AppSecret',
position: 'left',
module: '应用接入',
tipsData: tipsDataVal,
}"
>
</el-input>
// 表格中使用
<el-table-column prop="name" width="180">
<template slot="header">
<span
v-tip="{
term: 'AppId',
module: '应用接入',
tipsData: tipsDataVal,
}"
>
名称</span
>
</template>
</el-table-column>
扩展
import Vue from 'vue'; // 基于 Vue 构造器,创建一个“子类 const AlertComponent = Vue.extend({ template: '<div>{{ message }}</div>', data () { return { message: 'Hello, Aresn' }; }, }); // 此时的 component 已经是一个标准的 Vue 组件实例,因此它的 $el 属性也可以被访问: const component = new AlertComponent().$mount(); document.body.appendChild(component.$el); // $mount 也有一些快捷的挂载方式,以下两种都是可以的: // 在 $mount 里写参数来指定挂载的节点new AlertComponent().$mount('#app'); // 不用 $mount,直接在创建实例时指定 el 选项new AlertComponent({ el: '#app' }); 实现同样的效果,除了用 extend 外,也可以直接创建 Vue 实例,并且用一个 Render 函数来渲染一个 .vue 文件: import Vue from 'vue'; import Notification from './notification.vue'; const props = {}; // 这里可以传入一些组件的 props 选项 const Instance = new Vue({ render (h) { return h(Notification, { props: props }); } }); const component = Instance.$mount(); document.body.appendChild(component.$el); 渲染后,如果想操作 Render 的 Notification 实例: const notification = Instance.$children[0];
本文来自博客园,作者:JeckHui;
个人主页:前端实用站点推荐; 热榜资讯早读:热榜资讯-导航;
转载请注明原文链接:https://www.cnblogs.com/xiaohuizhang/p/16866607.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)