reco
reco

Reputation: 305

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 :

<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 .

Upvotes: 4

Views: 5831

Answers (1)

David L
David L

Reputation: 33833

Your use of the createElement method is incorrect when building your button, since you are passing the wrong series of arguments.

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:

// {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:

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:

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

See this working codepen.

Upvotes: 7

Related Questions