【前端开发】如何将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];
复制代码

 

posted @   JeckHui  阅读(406)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示