简体   繁体   English

vue.js 将事件监听器添加到渲染函数中的按钮

[英]vue.js add event listener to button in Render function

I want using Vue.js Render function to make component in javascript.Now I can make a HTML structure one SPAN and one BUTTON.when I click the button,I expect it output in console,but it just not work.here is my code :我想使用 Vue.js Render 函数在 javascript 中制作组件。现在我可以制作一个 SPAN 和一个 BUTTON 的 HTML 结构。当我单击按钮时,我希望它在控制台中输出,但它不起作用。这是我的代码:

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
  <counter></counter>
</div>
<script>
    var a = {
           data () {
              return {count: 1}
            },
            methods: {
              inc () {console.log(this.count)}
            },
            render:function(h){
              var self = this
              var buttonAttrs ={
                    on:{click:self.inc}
                  }
              var span = h('span',this.count.toString(),{},[])
              var button = h('button','+',buttonAttrs,[])
              return h('div' 
                ,{},
                [
                  span,
                  button
                ])

            }
      }

  new Vue({
    el:'#app',
    components:{
      counter : a
     }}
  )

</script>

or on codepen Any response is welcome and thank you .或在codepen欢迎任何回复,谢谢。

Your use of the createElement method is incorrect when building your button, since you are passing the wrong series of arguments.在构建按钮时,您对createElement方法的使用不正确,因为您传递了错误的一系列参数。

First off, you should set the inner html + via your button attributes object, not via the second argument which is reserved for the data object, per the documentation :首先,根据文档,您应该通过按钮属性对象设置内部 html + ,而不是通过为数据对象保留的第二个参数:

 // {Object} // A data object corresponding to the attributes // you would use in a template. Optional. { // (see details in the next section below) },

As such, you should structure your buttonsAttrs object as follows:因此,您应该按如下方式构建您的 buttonAttrs 对象:

var buttonAttrs = {
    on: { click: self.inc },
    domProps: {
        innerHTML: '+'
    },
};

Second, you should pass the buttonAttrs as the second argument in your createElement call per the above documentation:其次,您应该根据上述文档在createElement调用中将 buttonAttrs 作为第二个参数传递:

var button = h('button', buttonAttrs, []);

See this working codepen .请参阅此工作代码笔

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM