如何使用 createElement 在 Render 方法上定义 Vue 事件 [英] How to define Vue Events on Render Method using createElement

查看:81
本文介绍了如何使用 createElement 在 Render 方法上定义 Vue 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ElementUi NavMenu,并使用 createElement 方法渲染函数来制作菜单项,只使用带有菜单标题和索引的 JSON,只是 HTML 和 JS 文件,而不是 .vue 文件.

I'm using ElementUi NavMenu, and render function with the createElement method to make the items of the menu just using JSON with titles and index of the menu, just HTML and JS files, not .vue files.

菜单已挂载,单击时会显示子菜单,但子菜单 (el-menu-item) 的操作不起作用.我什至尝试属性 click, item-click, v-on: click when created the-menu-item (ElementUi 的文档告诉必须使用 @click ,但这会导致 @click 出现错误code>createElement 定义属性时),但是没有人工作,没有错误发生,就像没有声明方法一样.

The menu is mounted, the submenus are shown when I click it, but the actions of the submenu (el-menu-item) does not work. I even try the attributes click, item-click, v-on: click when creating the-menu-item (the documentation of ElementUi tells that @click must be used, but this causes an error on createElement when the attributes are defined), but no one works, no error occurs, as if the method was not been declared.

el-menu-item 上只有 onclick 属性有效,但是当我使用它时,vue 组件的方法没有被调用,所以我必须在组件之外创建一个函数(on例如一个类),当这个函数被调用时,它会调用组件方法(我尝试$发出)并发生错误,因为找不到组件的方法.

Only onclick attribute works on the el-menu-item, but when I use it, the method of vue component is not called, and so I have to make a function outside of component (on a class for example), and when this function is called it performs a call to component method (I try $ emits) and an error occurs, because the method of component is not found.

如何在组件的render函数中的el-menu-item中添加@click(或类似的)事件来调用同一个组件的方法?

How can I add @click (or similar) event on the el-menu-item inside render function of the component to call a method of the same component?

ElementUI 的 NavMenu 文档.

我如何创建菜单项:

createElement("el-menu-item",{
    attrs:{
        index:json[i].id,
        click:json[i].onclick
    }},
    json[i].title
)

推荐答案

其实这个在 Vue.js 文档中有提到.

Actually, this is mentioned in Vue.js documentation.

参见 https://vuejs.org/v2/guide/render-function.html#The-Data-Object-In-Depth .

例如https://codepen.io/jacobgoh101/pen/ypjGqw?editors=0010

Vue.component("test", {
  render: function(createElement) {
    return createElement(
      "button",
      {
        on: {
          click: function() {
            alert('click');
          }
        }
      },
      "Header"
    );
  }
});

这篇关于如何使用 createElement 在 Render 方法上定义 Vue 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆